-
-
Notifications
You must be signed in to change notification settings - Fork 504
Expand file tree
/
Copy pathtree_view.dart
More file actions
1564 lines (1429 loc) · 50.3 KB
/
tree_view.dart
File metadata and controls
1564 lines (1429 loc) · 50.3 KB
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:collection';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// A callback that receives a notification that the selection state of
/// a TreeView has changed.
///
/// Used by [TreeView.onSelectionChanged]
typedef TreeViewSelectionChangedCallback =
Future<void> Function(Iterable<TreeViewItem> selectedItems);
/// A callback that receives a notification that an item has been invoked.
///
/// Used by [TreeView.onItemInvoked]
typedef TreeViewItemInvoked =
Future<void> Function(TreeViewItem item, TreeViewItemInvokeReason reason);
/// A callback that receives a notification that an item
/// received a secondary tap.
///
/// Used by [TreeView.onSecondaryTap]
typedef TreeViewItemOnSecondaryTap =
void Function(TreeViewItem item, TapDownDetails details);
/// A callback that receives a notification that the expansion state of an
/// item has been toggled.
///
/// Used by [TreeView.onItemExpandToggle]
typedef TreeViewItemOnExpandToggle =
Future<void> Function(TreeViewItem item, bool getsExpanded);
/// A callback that returns the gestures for a [TreeViewItem].
///
/// Used by [TreeView.gesturesBuilder]
typedef TreeViewItemGesturesCallback =
Map<Type, GestureRecognizerFactory> Function(TreeViewItem item);
const double _whiteSpace = 8;
/// Default loading indicator used by [TreeView]
const Widget kTreeViewLoadingIndicator = Padding(
// Padding to make it the same width as the expand icon
padding: EdgeInsetsDirectional.only(start: 6, end: 6),
child: SizedBox(height: 12, width: 12, child: ProgressRing(strokeWidth: 3)),
);
/// The selection mode of a [TreeView].
///
/// See also:
///
/// * [TreeView], which uses this to determine the selection mode
/// * [TreeViewSelectionMode.none], which is used by default
/// * [TreeViewSelectionMode.single], which is used when only one item can be selected
/// * [TreeViewSelectionMode.multiple], which is used when multiple items can be selected
enum TreeViewSelectionMode {
/// Selection is disabled
none,
/// When single selection is enabled, only a single item can be selected by
/// once.
single,
/// When multiple selection is enabled, a checkbox is shown next to each tree
/// view item, and selected items are highlighted. A user can select or
/// de-select an item by using the checkbox; clicking the item still causes
/// it to be invoked.
///
/// Selecting or de-selecting a parent item will select or de-select all
/// children under that item. If some, but not all, of the children under a
/// parent item are selected, the checkbox for the parent node is shown in
/// the indeterminate state
///
/// 
multiple,
}
/// The reason that a [TreeViewItem] was invoked
enum TreeViewItemInvokeReason {
/// The item was expanded/collapsed
expandToggle,
/// The item selection state was toggled
selectionToggle,
/// The item was pressed
pressed,
}
/// An item displayed in a [TreeView] hierarchy.
///
/// Each [TreeViewItem] represents a node in the tree and can contain:
///
/// * [leading] - An optional widget displayed before the content (usually an icon)
/// * [content] - The main content of the item (usually text)
/// * [children] - Nested child items for hierarchical structure
///
/// {@tool snippet}
/// This example shows how to create tree view items:
///
/// ```dart
/// TreeViewItem(
/// content: Text('Documents'),
/// leading: Icon(FluentIcons.folder),
/// children: [
/// TreeViewItem(
/// content: Text('Report.docx'),
/// leading: Icon(FluentIcons.document),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [TreeView], which renders a collection of [TreeViewItem]s
/// * <https://learn.microsoft.com/en-us/windows/apps/design/controls/tree-view>
class TreeViewItem with Diagnosticable {
/// {@macro flutter.widgets.Widget.key}
final Key? key;
/// The item leading
///
/// Usually an [Icon] widget
final Widget? leading;
/// The item content
///
/// Usually a [Text] widget
final Widget content;
/// An optional/arbitrary value associated with the item.
///
/// For example, a primary key of the row of data that this
/// item is associated with.
final dynamic value;
/// The children of this item.
///
/// This list is unmodifiable. To add, remove, or reorder children, use
/// [TreeViewController.addItem], [TreeViewController.removeItem], or
/// [TreeViewController.moveItem].
List<TreeViewItem> get children => _unmodifiableChildren;
late final UnmodifiableListView<TreeViewItem> _unmodifiableChildren =
UnmodifiableListView(_children);
final List<TreeViewItem> _children;
/// Whether the item can be collapsable by user-input or not.
///
/// Defaults to `true`
final bool collapsable;
TreeViewItem? _parent;
/// Whether the item has any siblings (including itself) that are expandable
bool _anyExpandableSiblings;
/// [TreeViewItem] that owns the [children] collection that this node is part
/// of.
///
/// If null, this is the root node
TreeViewItem? get parent => _parent;
/// Whether the current item is expanded.
///
/// It has no effect if [children] is empty.
bool expanded;
/// Whether the current item is selected.
///
/// If [TreeView.selectionMode] is [TreeViewSelectionMode.none], this has no
/// effect. If it's [TreeViewSelectionMode.single], this item is going to be
/// the only selected item. If it's [TreeViewSelectionMode.multiple], this
/// item is going to be one of the selected items
bool? selected;
/// Called when this item is invoked
///
/// This item is passed to the callback.
///
/// This callback is executed __after__ the global
/// [TreeView.onItemInvoked]-callback.
final TreeViewItemInvoked? onInvoked;
/// Called when this item's expansion state is toggled.
///
/// This item and its future expand state are passed to the callback.
///
/// This callback is executed __after__ the global
/// [TreeView.onItemExpandToggle]-callback.
final TreeViewItemOnExpandToggle? onExpandToggle;
/// The gestures that this item will respond to.
///
/// See also:
///
/// * [TreeView.gesturesBuilder], which builds gestures for each item
final Map<Type, GestureRecognizerFactory> gestures;
/// The background color of this item.
///
/// See also:
///
/// * [ButtonThemeData.uncheckedInputColor], which is used by default
final WidgetStateColor? backgroundColor;
/// Whether this item is visible or not. Used to not lose the item state while
/// it's not on the screen
bool _visible = true;
/// {@macro flutter.widgets.Focus.autofocus}
final bool autofocus;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode focusNode;
/// Whether the node is focused by press
bool _focusedByPress = false;
/// {@macro fluent_ui.controls.inputs.HoverButton.semanticLabel}
final String? semanticLabel;
/// Whether the tree view item is loading
bool loading = false;
/// Widget to show when [loading]
///
/// If null, [TreeView.loadingWidget] is used instead
final Widget? loadingWidget;
/// Whether this item children is loaded lazily
final bool lazy;
/// Creates a tree view item.
TreeViewItem({
required this.content,
this.key,
this.leading,
this.value,
List<TreeViewItem> children = const [],
this.collapsable = true,
bool? expanded,
this.selected = false,
this.onInvoked,
this.onExpandToggle,
this.gestures = const {},
this.backgroundColor,
this.autofocus = false,
FocusNode? focusNode,
this.semanticLabel,
this.loadingWidget,
this.lazy = false,
}) : _children = List.of(children),
expanded = expanded ?? children.isNotEmpty,
_anyExpandableSiblings = false,
focusNode = focusNode ?? FocusNode();
/// Deep copy constructor that can be used to copy an item and all of
/// its child items. Useful if you want to have multiple trees with the
/// same items, but with different UX states (e.g., selection, visibility,
/// etc.).
factory TreeViewItem.from(TreeViewItem source) {
final newItem = TreeViewItem(
key: source.key,
leading: source.leading,
content: source.content,
value: source.value,
children: source.children.map(TreeViewItem.from).toList(),
collapsable: source.collapsable,
expanded: source.expanded,
selected: source.selected,
onInvoked: source.onInvoked,
onExpandToggle: source.onExpandToggle,
backgroundColor: source.backgroundColor,
autofocus: source.autofocus,
focusNode: source.focusNode,
semanticLabel: source.semanticLabel,
loadingWidget: source.loadingWidget,
lazy: source.lazy,
);
for (final c in newItem.children) {
c._parent = newItem;
}
return newItem;
}
/// Whether this node is expandable
bool get isExpandable {
return lazy || children.isNotEmpty;
}
/// Indicates how far from the root node this child node is.
///
/// If this is the root node, the depth is 0
int get depth {
if (parent != null) {
var count = 1;
var currentParent = parent;
while (currentParent?.parent != null) {
count++;
currentParent = currentParent?.parent;
}
return count;
}
return 0;
}
/// Gets the last parent in the tree, in decrescent order.
///
/// If this is the root parent, [this] is returned
TreeViewItem get lastParent {
if (parent != null) {
var currentParent = parent!;
while (currentParent.parent != null) {
if (currentParent.parent != null) currentParent = currentParent.parent!;
}
return currentParent;
}
return this;
}
/// Executes [callback] for every parent found in the tree
void executeForAllParents(ValueChanged<TreeViewItem?> callback) {
if (parent == null) return;
var currentParent = parent;
callback(currentParent);
while (currentParent?.parent != null) {
currentParent = currentParent?.parent;
callback(currentParent);
}
}
/// Changes the selection state for this item and all of its children
/// to either all selected or all deselected. Also appropriately updates
/// the selection state of this item's parents as required. This should not
/// be used for an item that belongs to a [TreeView] in single selection
/// mode. See also [TreeView.deselectParentWhenChildrenDeselected].
void setSelectionStateForMultiSelectionMode(
bool newSelectionState,
bool deselectParentWhenChildrenDeselected,
) {
selected = newSelectionState;
children.executeForAll((item) {
item.selected = newSelectionState;
});
executeForAllParents(
(p) => p?.updateSelected(deselectParentWhenChildrenDeselected),
);
}
/// Updates [selected] based on the direct [children]s' state.
/// [selected] will not be forced to false if
/// `deselectParentWhenChildrenDeselected` is false and
/// either there are no children or all children are deselected.
///
/// Since this only updates the state based on direct children,
/// you would normally only call this in a depth-first manner on
/// all parents, for example:
///
/// ```dart
/// item.executeForAllParents((parent) => parent
/// ?.updateSelected(widget.deselectParentWhenChildrenDeselected))
/// ```
void updateSelected(bool deselectParentWhenChildrenDeselected) {
var hasNull = false;
var hasFalse = false;
var hasTrue = false;
for (final child in children) {
if (child.selected == null) {
hasNull = true;
} else if (child.selected == false) {
hasFalse = true;
} else if (child.selected ?? false) {
hasTrue = true;
}
}
if (!deselectParentWhenChildrenDeselected &&
(children.isEmpty || (!hasNull && hasFalse && !hasTrue))) {
if (selected == null && children.isEmpty) {
// should not be possible unless children were removed after the
// selected was updated previously...
selected = true;
} else if (selected ?? false) {
// we're now only in a partially selected state
selected = null;
}
} else {
selected = hasNull || (hasTrue && hasFalse) ? null : hasTrue;
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
..add(
FlagProperty(
'hasLeading',
value: leading != null,
ifFalse: 'no leading',
),
)
..add(
FlagProperty(
'hasChildren',
value: children.isNotEmpty,
ifFalse: 'has children',
),
)
..add(
FlagProperty(
'collapsable',
value: collapsable,
defaultValue: true,
ifFalse: 'uncollapsable',
),
)
..add(
FlagProperty(
'isRootNode',
value: parent == null,
ifFalse: 'has parent',
),
)
..add(
FlagProperty(
'expanded',
value: expanded,
defaultValue: true,
ifFalse: 'collapsed',
),
)
..add(
FlagProperty(
'selected',
value: selected,
defaultValue: false,
ifFalse: 'unselected',
),
)
..add(
FlagProperty(
'loading',
value: loading,
defaultValue: false,
ifFalse: 'not loading',
),
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is TreeViewItem &&
other.key == key &&
other.leading == leading &&
other.content == content &&
other.value == value &&
listEquals(other._children, _children) &&
other.collapsable == collapsable &&
other._anyExpandableSiblings == _anyExpandableSiblings &&
other.selected == selected &&
other.onInvoked == onInvoked &&
other.onExpandToggle == onExpandToggle &&
other.backgroundColor == backgroundColor &&
other._visible == _visible &&
other.autofocus == autofocus &&
other.focusNode == focusNode &&
other.semanticLabel == semanticLabel &&
other.loading == loading &&
other.loadingWidget == loadingWidget &&
other.lazy == lazy;
}
@override
int get hashCode {
return key.hashCode ^
leading.hashCode ^
content.hashCode ^
value.hashCode ^
_children.hashCode ^
collapsable.hashCode ^
_anyExpandableSiblings.hashCode ^
selected.hashCode ^
onInvoked.hashCode ^
onExpandToggle.hashCode ^
backgroundColor.hashCode ^
_visible.hashCode ^
autofocus.hashCode ^
focusNode.hashCode ^
semanticLabel.hashCode ^
loading.hashCode ^
loadingWidget.hashCode ^
lazy.hashCode;
}
}
/// An extension on [List<TreeViewItem>] that adds methods to build the tree view.
extension TreeViewItemCollection on List<TreeViewItem> {
/// Adds the [TreeViewItem.parent] property to the [TreeViewItem]s
/// and calculates other internal properties.
List<TreeViewItem> build({TreeViewItem? parent}) {
if (isNotEmpty) {
final list = <TreeViewItem>[];
final anyExpandableSiblings = any((i) => i.isExpandable);
for (final item in this) {
item
.._parent = parent
.._anyExpandableSiblings = anyExpandableSiblings;
if (parent != null) {
item._visible = parent._visible;
}
if (item._visible) {
list.add(item);
}
final itemAnyExpandableSiblings = item.children.any(
(i) => i.isExpandable,
);
for (final child in item.children) {
// only add the children when it's expanded and visible
child
.._visible = item.expanded && item._visible
.._parent = item
.._anyExpandableSiblings = itemAnyExpandableSiblings;
if (child._visible) {
list.add(child);
}
if (child.expanded) {
list.addAll(child.children.build(parent: child));
}
}
}
return list;
}
return this;
}
/// Executes the [callback] for all items in the tree view and all their
/// children, recursively.
void executeForAll(ValueChanged<TreeViewItem> callback) {
for (final child in this) {
callback(child);
child.children.executeForAll(callback);
}
}
/// Returns an iteration of all items in the tree view and all their
/// children, recursively, that satisfy the [t] predicate.
Iterable<TreeViewItem> whereForAll(bool Function(TreeViewItem element) t) {
var result = where(t);
for (final child in this) {
result = result.followedBy(child.children.whereForAll(t));
}
return result;
}
/// Returns an iteration of all selected items (optionally including items
/// that are only partially selected).
Iterable<TreeViewItem> selectedItems(bool includePartiallySelectedItems) {
return whereForAll(
(item) =>
(item.selected ?? false) ||
(includePartiallySelectedItems && item.selected == null),
);
}
}
/// A controller for a [TreeView].
///
/// A [TreeViewController] provides programmatic control over a [TreeView],
/// including managing items, selection, and expansion state.
///
/// This is similar to [ScrollController] or [TextEditingController] in Flutter.
///
/// {@tool snippet}
/// This example shows how to use a TreeViewController:
///
/// ```dart
/// final controller = TreeViewController(
/// items: [
/// TreeViewItem(content: Text('Item 1'), value: 'item1'),
/// TreeViewItem(content: Text('Item 2'), value: 'item2'),
/// ],
/// );
///
/// TreeView(controller: controller);
///
/// // Later, programmatically manipulate the tree:
/// controller.expandAll();
/// controller.addItem(TreeViewItem(content: Text('New'), value: 'new'));
/// controller.addItems([...], parent: someItem);
/// controller.moveItem(someItem, newParent: targetItem);
/// controller.selectItem(controller.items.first);
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [TreeView], which this controller manages
/// * [TreeViewItem], the data model for tree nodes
class TreeViewController with ChangeNotifier, Diagnosticable {
/// Creates a [TreeViewController].
///
/// If [items] is provided, the controller will manage those items.
TreeViewController({List<TreeViewItem>? items}) : _items = items ?? [];
List<TreeViewItem> _items;
TreeViewState? _state;
/// The items managed by this controller.
List<TreeViewItem> get items => _items;
/// Sets the items managed by this controller and rebuilds the tree.
set items(List<TreeViewItem> value) {
_items = value;
_rebuild();
}
/// Whether this controller is attached to a [TreeView].
bool get isAttached => _state != null;
/// Attaches this controller to a [TreeViewState].
// ignore: use_setters_to_change_properties
void _attach(TreeViewState state) {
_state = state;
}
/// Detaches this controller from a [TreeViewState].
void _detach() {
_state = null;
}
/// Rebuilds the tree view by notifying listeners.
///
/// When attached to a [TreeViewState], the listener mechanism
/// triggers the state rebuild.
void _rebuild() {
notifyListeners();
}
/// Finds a [TreeViewItem] by its [value].
///
/// Returns the first item whose [TreeViewItem.value] equals [value],
/// or `null` if no such item exists. Searches recursively through all
/// children.
TreeViewItem? getItemFromValue(dynamic value) {
return _findItemByValue(_items, value);
}
static TreeViewItem? _findItemByValue(
List<TreeViewItem> items,
dynamic value,
) {
for (final item in items) {
if (item.value == value) return item;
final found = _findItemByValue(item._children, value);
if (found != null) return found;
}
return null;
}
/// Adds [item] as a child of [parent].
///
/// If [parent] is null, the item is added to the root level.
/// If [index] is provided, the item is inserted at that position;
/// otherwise, it's appended to the end.
void addItem(TreeViewItem item, {TreeViewItem? parent, int? index}) {
final target = parent?._children ?? _items;
if (index != null) {
target.insert(index, item);
} else {
target.add(item);
}
_rebuild();
}
/// Adds multiple [items] as children of [parent].
///
/// If [parent] is null, items are added to the root level.
/// This is more efficient than calling [addItem] multiple times
/// because it only triggers a single rebuild.
void addItems(List<TreeViewItem> items, {TreeViewItem? parent}) {
final target = parent?._children ?? _items;
target.addAll(items);
_rebuild();
}
/// Removes [item] from the tree.
///
/// Returns `true` if the item was found and removed, `false` otherwise.
bool removeItem(TreeViewItem item) {
final parent = item.parent;
final removed = parent != null
? parent._children.remove(item)
: _items.remove(item);
if (removed) _rebuild();
return removed;
}
/// Moves [item] to a new position in the tree.
///
/// If [newParent] is provided, the item is moved as a child of that parent.
/// If [newParent] is null, the item is moved to the root level.
/// If [index] is provided, the item is inserted at that position;
/// otherwise, it's appended to the end.
///
/// Returns `true` if the item was successfully moved, `false` if the item
/// could not be removed from its current position.
bool moveItem(TreeViewItem item, {TreeViewItem? newParent, int? index}) {
// Remove from old position
final oldParent = item.parent;
final removed = oldParent != null
? oldParent._children.remove(item)
: _items.remove(item);
if (!removed) return false;
// Insert at new position
final target = newParent?._children ?? _items;
if (index != null && index <= target.length) {
target.insert(index, item);
} else {
target.add(item);
}
_rebuild();
return true;
}
/// Expands [item] if it has children.
void expandItem(TreeViewItem item) {
if (item.children.isNotEmpty || item.lazy) {
item.expanded = true;
_rebuild();
}
}
/// Collapses [item].
void collapseItem(TreeViewItem item) {
item.expanded = false;
_rebuild();
}
/// Expands all items in the tree recursively.
void expandAll() {
_items.executeForAll((item) {
if (item.children.isNotEmpty || item.lazy) {
item.expanded = true;
}
});
_rebuild();
}
/// Collapses all items in the tree recursively.
void collapseAll() {
_items.executeForAll((item) {
item.expanded = false;
});
_rebuild();
}
/// Selects [item].
///
/// In single selection mode, this deselects all other items first.
void selectItem(TreeViewItem item) {
item.selected = true;
_rebuild();
}
/// Deselects [item].
void deselectItem(TreeViewItem item) {
item.selected = false;
_rebuild();
}
/// Selects all items in the tree recursively.
void selectAll() {
_items.executeForAll((item) {
item.selected = true;
});
_rebuild();
}
/// Deselects all items in the tree recursively.
void deselectAll() {
_items.executeForAll((item) {
item.selected = false;
});
_rebuild();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
..add(IntProperty('itemCount', _items.length))
..add(
FlagProperty(
'isAttached',
value: isAttached,
ifTrue: 'attached',
ifFalse: 'detached',
),
);
}
@override
void dispose() {
_detach();
super.dispose();
}
}
/// A hierarchical list with expanding and collapsing nodes.
///
/// [TreeView] displays nested items in a tree structure, using indentation
/// and icons to show parent-child relationships. It's ideal for displaying
/// folder structures, organizational hierarchies, or any nested data.
///
/// Use a [TreeViewController] to programmatically control the tree:
///
/// 
///
/// {@tool snippet}
/// This example shows a basic tree view with a controller:
///
/// ```dart
/// final controller = TreeViewController(
/// items: [
/// TreeViewItem(
/// content: Text('Folder 1'),
/// children: [
/// TreeViewItem(content: Text('File 1')),
/// TreeViewItem(content: Text('File 2')),
/// ],
/// ),
/// TreeViewItem(content: Text('Folder 2')),
/// ],
/// );
///
/// TreeView(controller: controller)
/// ```
/// {@end-tool}
///
/// ## Selection modes
///
/// * [TreeViewSelectionMode.none] - Selection is disabled
/// * [TreeViewSelectionMode.single] - Only one item can be selected
/// * [TreeViewSelectionMode.multiple] - Multiple items can be selected with checkboxes
///
/// 
///
/// See also:
///
/// * [TreeViewItem], the data model for tree nodes
/// * [ListView], for non-hierarchical lists
/// * <https://learn.microsoft.com/en-us/windows/apps/design/controls/tree-view>
class TreeView extends StatefulWidget {
/// Creates a tree view.
///
/// [items] are provided directly for simple use cases. For programmatic
/// control, provide a [controller] instead or in addition.
const TreeView({
this.items = const [],
this.controller,
super.key,
this.selectionMode = TreeViewSelectionMode.none,
this.onSelectionChanged,
this.onItemInvoked,
this.onItemExpandToggle,
this.onSecondaryTap,
this.gesturesBuilder,
this.loadingWidget = kTreeViewLoadingIndicator,
this.shrinkWrap = true,
this.scrollPrimary,
this.scrollController,
this.cacheExtent,
this.itemExtent,
this.addRepaintBoundaries = true,
this.usePrototypeItem = false,
this.narrowSpacing = false,
this.includePartiallySelectedItems = false,
this.deselectParentWhenChildrenDeselected = true,
});
/// The items of the tree view.
///
/// When a [controller] is provided, the controller's items take precedence.
/// Items can be declared inline directly in the [TreeView] constructor.
final List<TreeViewItem> items;
/// An optional controller that manages the tree view's items and state.
///
/// When provided, the controller's items take precedence over [items].
/// The controller provides programmatic access to add, remove,
/// expand, collapse, select, deselect, and move items.
///
/// See also:
///
/// * [TreeViewController], which this parameter accepts
final TreeViewController? controller;
/// The current selection mode.
///
/// [TreeViewSelectionMode.none] is used by default
final TreeViewSelectionMode selectionMode;
/// If [selectionMode] is [TreeViewSelectionMode.multiple], indicates if
/// a parent will automatically be deselected when all of its children
/// are deselected. If you disable this behavior, also consider if you
/// want to set [includePartiallySelectedItems] to true.
final bool deselectParentWhenChildrenDeselected;
/// Called when an item is invoked
///
/// The item invoked is passed to the callback.
///
/// This callback is executed __before__ the item's own
/// [TreeViewItem.onInvoked]-callback.
final TreeViewItemInvoked? onItemInvoked;
/// Called when an item's expand state is toggled.
///
/// The item and its future expand state are passed to the callback.
/// The callback is executed before the item's expand state actually changes.
///
/// This callback is executed __before__ the item's own
/// [TreeViewItem.onExpandToggle]-callback.
final TreeViewItemOnExpandToggle? onItemExpandToggle;
/// A tap with a secondary button has occurred.
///
/// The item tapped and [TapDownDetails] are passed to the callback.
final TreeViewItemOnSecondaryTap? onSecondaryTap;
/// A callback that receives a notification that the gestures for an item
///
/// This is called alongside [TreeViewItem.gestures]
final TreeViewItemGesturesCallback? gesturesBuilder;
/// Called when the selection changes. The items that are currently
/// selected will be passed to the callback. This could be empty
/// if nothing is now selected. If [TreeView.selectionMode] is
/// [TreeViewSelectionMode.single] then it will contain exactly
/// zero or one items.
final TreeViewSelectionChangedCallback? onSelectionChanged;
/// If true, will include items that are in an indeterminute (partially
/// selected) state in the list of selected items in the
/// [onSelectionChanged] callback.
final bool includePartiallySelectedItems;
/// A widget to be shown when a node is loading. Only used if
/// [TreeViewItem.loadingWidget] is null.
///
/// [kTreeViewLoadingIndicator] is used by default
final Widget loadingWidget;
/// {@macro flutter.widgets.scroll_view.shrinkWrap}
final bool shrinkWrap;
/// {@macro flutter.widgets.scroll_view.primary}
final bool? scrollPrimary;
/// {@macro flutter.widgets.scroll_view.controller}
final ScrollController? scrollController;
/// {@macro flutter.rendering.RenderViewportBase.cacheExtent}
final double? cacheExtent;
/// {@macro flutter.widgets.list_view.itemExtent}
final double? itemExtent;
/// Whether to wrap each child in a [RepaintBoundary].
///
/// Typically, children in a scrolling container are wrapped in repaint
/// boundaries so that they do not need to be repainted as the list scrolls.
/// If the children are easy to repaint (e.g., solid color blocks or a short
/// snippet of text), it might be more efficient to not add a repaint boundary
/// and simply repaint the children during scrolling.
///
/// Defaults to true.
final bool addRepaintBoundaries;
/// Whether or not to give the internal [ListView] a prototype item based on
/// the first item in the tree view. Set this to true to allow the ListView to
/// more efficiently calculate the maximum scrolling extent, and it will force
/// the vertical size of each item to be the same size as the first item in
/// the tree view.
///
/// {@macro flutter.widgets.list_view.prototypeItem}
///
/// Defaults to false.
///