This article focuses on looking at TreeView examples that are simple to reuse. We have an excellent tool for representing hierarchical data in a widget like a Flutter Tree View.
A few points that make this widget helpful to create a flutter app:
- highly adaptable. The UI is designed by yourself, and it solely manages the data’s tree structure.
- The reuse mechanism of the ListView widget makes performance efficient.
- Growing child levels and child nodes indefinitely.
- data import from a map
- features convenient ways to create, update, and remove nodes.
You may also check our Flutter app development page
Let’s start flutter tree view implementation with a demo mobikul flutter app in a few easy steps.
1) Project Setup:
Create a new flutter project and add latest flutter_treeview version under dependencies in pubspec.yaml file of your project as following example and run flutter pub get command to install the package in your project.
1 2 3 |
dependencies: flutter_treeview: ^1.0.7+1 |
2) Import package:
Import flutter tree view using following line in the class you need to implement this functionality.
1 |
import 'package:flutter_treeview/flutter_treeview.dart'; |
3) Creates Nodes:
We need to create a list of node with its children as per our requirement as following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
_nodes = [ Node( label: 'documents', key: 'docs', expanded: docsOpen, icon: docsOpen ? Icons.folder_open : Icons.folder, children: [ Node( label: 'personal', key: 'd3', icon: Icons.input, iconColor: Colors.red, children: [ Node( label: 'Poems.docx', key: 'pd1', icon: Icons.insert_drive_file, ), Node( label: 'Job Hunt', key: 'jh1', icon: Icons.input, children: [ Node( label: 'Resume.docx', key: 'jh1a', icon: Icons.insert_drive_file, ), Node( label: 'Cover Letter.docx', key: 'jh1b', icon: Icons.insert_drive_file, ), ], ), ], ), Node( label: 'Inspection.docx', key: 'd1', // icon: Icons.insert_drive_file), ), Node(label: 'Invoice.docx', key: 'd2', icon: Icons.insert_drive_file), ], ), Node( label: 'MeetingReport.xls', key: 'mrxls', icon: Icons.insert_drive_file), ]; |
4. Create a Map:
We need list of map data as per our requirement as following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
const List<Map<String, dynamic>> US_STATES = [ { "label": "A", "children": [ {"label": "Alabama", "key": "AL"}, {"label": "Alaska", "key": "AK"}, {"label": "American Samoa", "key": "AS"}, {"label": "Arizona", "key": "AZ"}, {"label": "Arkansas", "key": "AR"} ] }, { "label": "C", "children": [ {"label": "California", "key": "CA"}, {"label": "Colorado", "key": "CO"}, {"label": "Connecticut", "key": "CT"}, ] }, ]; String US_STATES_JSON = jsonEncode(US_STATES); |
5. Complete Implementation:
Here we have complete implementation of flutter tree view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
import 'package:example/states.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_treeview/flutter_treeview.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'TreeView Example', home: MyHomePage(title: 'TreeView Example'), theme: ThemeData().copyWith( accentColor: Colors.deepPurple, hoverColor: Colors.red.shade100, colorScheme: ThemeData().colorScheme.copyWith(primary: Colors.red), ), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { String _selectedNode; List<Node> _nodes; TreeViewController _treeViewController; bool docsOpen = true; bool deepExpanded = true; final Map<ExpanderPosition, Widget> expansionPositionOptions = const { ExpanderPosition.start: Text('Start'), ExpanderPosition.end: Text('End'), }; final Map<ExpanderType, Widget> expansionTypeOptions = { ExpanderType.none: Container(), ExpanderType.caret: Icon( Icons.arrow_drop_down, size: 28, ), ExpanderType.arrow: Icon(Icons.arrow_downward), ExpanderType.chevron: Icon(Icons.expand_more), ExpanderType.plusMinus: Icon(Icons.add), }; final Map<ExpanderModifier, Widget> expansionModifierOptions = const { ExpanderModifier.none: ModContainer(ExpanderModifier.none), ExpanderModifier.circleFilled: ModContainer(ExpanderModifier.circleFilled), ExpanderModifier.circleOutlined: ModContainer(ExpanderModifier.circleOutlined), ExpanderModifier.squareFilled: ModContainer(ExpanderModifier.squareFilled), ExpanderModifier.squareOutlined: ModContainer(ExpanderModifier.squareOutlined), }; ExpanderPosition _expanderPosition = ExpanderPosition.start; ExpanderType _expanderType = ExpanderType.caret; ExpanderModifier _expanderModifier = ExpanderModifier.none; bool _allowParentSelect = false; bool _supportParentDoubleTap = false; @override void initState() { _nodes = [ Node( label: 'documents', key: 'docs', expanded: docsOpen, icon: docsOpen ? Icons.folder_open : Icons.folder, children: [ Node( label: 'personal', key: 'd3', icon: Icons.input, iconColor: Colors.red, children: [ Node( label: 'Poems.docx', key: 'pd1', icon: Icons.insert_drive_file, ), Node( label: 'Job Hunt', key: 'jh1', icon: Icons.input, children: [ Node( label: 'Resume.docx', key: 'jh1a', icon: Icons.insert_drive_file, ), Node( label: 'Cover Letter.docx', key: 'jh1b', icon: Icons.insert_drive_file, ), ], ), ], ), Node( label: 'Inspection.docx', key: 'd1', // icon: Icons.insert_drive_file), ), Node(label: 'Invoice.docx', key: 'd2', icon: Icons.insert_drive_file), ], ), Node( label: 'MeetingReport.xls', key: 'mrxls', icon: Icons.insert_drive_file), Node( label: 'MeetingReport.pdf', key: 'mrpdf', iconColor: Colors.green.shade300, selectedIconColor: Colors.white, icon: Icons.insert_drive_file), Node(label: 'Demo.zip', key: 'demo', icon: Icons.archive), Node( label: 'empty folder', key: 'empty', parent: true, ), ]; _treeViewController = TreeViewController( children: _nodes, selectedKey: _selectedNode, ); super.initState(); } ListTile _makeExpanderPosition() { return ListTile( title: Text('Expander Position'), dense: true, trailing: CupertinoSlidingSegmentedControl( children: expansionPositionOptions, groupValue: _expanderPosition, onValueChanged: (ExpanderPosition newValue) { setState(() { _expanderPosition = newValue; }); }, ), ); } SwitchListTile _makeAllowParentSelect() { return SwitchListTile.adaptive( title: Text('Allow Parent Select'), dense: true, value: _allowParentSelect, onChanged: (v) { setState(() { _allowParentSelect = v; }); }, ); } SwitchListTile _makeSupportParentDoubleTap() { return SwitchListTile.adaptive( title: Text('Support Parent Double Tap'), dense: true, value: _supportParentDoubleTap, onChanged: (v) { setState(() { _supportParentDoubleTap = v; }); }, ); } ListTile _makeExpanderType() { return ListTile( title: Text('Expander Style'), dense: true, trailing: CupertinoSlidingSegmentedControl( children: expansionTypeOptions, groupValue: _expanderType, onValueChanged: (ExpanderType newValue) { setState(() { _expanderType = newValue; }); }, ), ); } ListTile _makeExpanderModifier() { return ListTile( title: Text('Expander Modifier'), dense: true, trailing: CupertinoSlidingSegmentedControl( children: expansionModifierOptions, groupValue: _expanderModifier, onValueChanged: (ExpanderModifier newValue) { setState(() { _expanderModifier = newValue; }); }, ), ); } @override Widget build(BuildContext context) { TreeViewTheme _treeViewTheme = TreeViewTheme( expanderTheme: ExpanderThemeData( type: _expanderType, modifier: _expanderModifier, position: _expanderPosition, // color: Colors.grey.shade800, size: 20, color: Colors.blue), labelStyle: TextStyle( fontSize: 16, letterSpacing: 0.3, ), parentLabelStyle: TextStyle( fontSize: 16, letterSpacing: 0.1, fontWeight: FontWeight.w800, color: Colors.blue.shade700, ), iconTheme: IconThemeData( size: 18, color: Colors.grey.shade800, ), colorScheme: Theme.of(context).colorScheme, ); return Scaffold( appBar: AppBar( title: Text(widget.title), elevation: 0, ), body: GestureDetector( onTap: () { FocusScope.of(context).requestFocus(FocusNode()); }, child: Container( padding: EdgeInsets.all(20), height: double.infinity, child: Column( children: <Widget>[ Container( height: 160, child: Column( children: <Widget>[ _makeExpanderPosition(), _makeExpanderType(), _makeExpanderModifier(), // _makeAllowParentSelect(), // _makeSupportParentDoubleTap(), ], ), ), Expanded( child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), ), padding: EdgeInsets.all(10), child: TreeView( controller: _treeViewController, allowParentSelect: _allowParentSelect, supportParentDoubleTap: _supportParentDoubleTap, onExpansionChanged: (key, expanded) => _expandNode(key, expanded), onNodeTap: (key) { debugPrint('Selected: $key'); setState(() { _selectedNode = key; _treeViewController = _treeViewController.copyWith(selectedKey: key); }); }, theme: _treeViewTheme, ), ), ), GestureDetector( onTap: () { debugPrint('Close Keyboard'); FocusScope.of(context).unfocus(); }, child: Container( padding: EdgeInsets.only(top: 20), alignment: Alignment.center, child: Text(_treeViewController.getNode(_selectedNode) == null ? '' : _treeViewController.getNode(_selectedNode).label), ), ) ], ), ), ), bottomNavigationBar: SafeArea( top: false, child: ButtonBar( alignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ CupertinoButton( child: Text('Node'), onPressed: () { setState(() { _treeViewController = _treeViewController.copyWith( children: _nodes, ); }); }, ), CupertinoButton( child: Text('JSON'), onPressed: () { setState(() { _treeViewController = _treeViewController.loadJSON(json: US_STATES_JSON); }); }, ), // CupertinoButton( // child: Text('Toggle'), // onPressed: _treeViewController.selectedNode != null && // _treeViewController.selectedNode.isParent // ? () { // setState(() { // _treeViewController = _treeViewController // .withToggleNode(_treeViewController.selectedKey); // }); // } // : null, // ), CupertinoButton( child: Text('Deep'), onPressed: () { String deepKey = 'jh1b'; setState(() { if (deepExpanded == false) { List<Node> newdata = _treeViewController.expandToNode(deepKey); _treeViewController = _treeViewController.copyWith(children: newdata); deepExpanded = true; } else { _treeViewController = _treeViewController.withCollapseToNode(deepKey); deepExpanded = false; } }); }, ), CupertinoButton( child: Text('Edit'), onPressed: () { TextEditingController editingController = TextEditingController( text: _treeViewController.selectedNode.label); showCupertinoDialog( context: context, builder: (context) { return CupertinoAlertDialog( title: Text('Edit Label'), content: Container( height: 80, alignment: Alignment.center, padding: EdgeInsets.all(10), child: CupertinoTextField( controller: editingController, autofocus: true, ), ), actions: <Widget>[ CupertinoDialogAction( child: Text('Cancel'), isDestructiveAction: true, onPressed: () => Navigator.of(context).pop(), ), CupertinoDialogAction( child: Text('Update'), isDefaultAction: true, onPressed: () { if (editingController.text.isNotEmpty) { setState(() { Node _node = _treeViewController.selectedNode; _treeViewController = _treeViewController.withUpdateNode( _treeViewController.selectedKey, _node.copyWith( label: editingController.text)); }); debugPrint(editingController.text); } Navigator.of(context).pop(); }, ), ], ); }); }, ), ], ), ), ); } _expandNode(String key, bool expanded) { String msg = '${expanded ? "Expanded" : "Collapsed"}: $key'; debugPrint(msg); Node node = _treeViewController.getNode(key); if (node != null) { List<Node> updated; if (key == 'docs') { updated = _treeViewController.updateNode( key, node.copyWith( expanded: expanded, icon: expanded ? Icons.folder_open : Icons.folder, )); } else { updated = _treeViewController.updateNode( key, node.copyWith(expanded: expanded)); } setState(() { if (key == 'docs') docsOpen = expanded; _treeViewController = _treeViewController.copyWith(children: updated); }); } } } class ModContainer extends StatelessWidget { final ExpanderModifier modifier; const ModContainer(this.modifier, {Key key}) : super(key: key); @override Widget build(BuildContext context) { double _borderWidth = 0; BoxShape _shapeBorder = BoxShape.rectangle; Color _backColor = Colors.transparent; Color _backAltColor = Colors.grey.shade700; switch (modifier) { case ExpanderModifier.none: break; case ExpanderModifier.circleFilled: _shapeBorder = BoxShape.circle; _backColor = _backAltColor; break; case ExpanderModifier.circleOutlined: _borderWidth = 1; _shapeBorder = BoxShape.circle; break; case ExpanderModifier.squareFilled: _backColor = _backAltColor; break; case ExpanderModifier.squareOutlined: _borderWidth = 1; break; } return Container( decoration: BoxDecoration( shape: _shapeBorder, border: _borderWidth == 0 ? null : Border.all( width: _borderWidth, color: _backAltColor, ), color: _backColor, ), width: 15, height: 15, ); } } |
Output:
Conclusion:
In this article, we have learned about tree view structure with a simple mobikul example app using flutter_treeview: ^1.0.7+1 plugin.
Thanks for reading the blog, for more such informative articles related to latest tech trend please visit our mobikul blog site.