embraceitmobile / animated_tree_view

Animated TreeView based on AnimatedList allows building fully customizable Nodes that can be nested to infinite levels and children.
https://pub.dev/packages/animated_tree_view
MIT License
49 stars 23 forks source link

Expand all nodes default or special node #5

Closed daonvshu closed 1 year ago

daonvshu commented 1 year ago

Hi, Is there any way to expand all child nodes or specified node after all view build is complete? I changed the 'isExpanded' property of the TreeNode to true but it had no effect.

jawwad-hassan89 commented 1 year ago

To programmatically expand or collapse a node, use the toggleExpansion method of the TreeViewController

To get the TreeViewController, wrap the TreeViewState inside a GlobalKey like final globalKey = GlobalKey<TreeViewState>(), and then get the controller from the currentState like this globalKey.currentState?.controller;

Full code sample to use the TreeViewController:

class _MyHomePageState extends State<MyHomePage> {
  final globalKey = GlobalKey<TreeViewState>();

  TreeViewController? get controller => globalKey.currentState?.controller;
  final tree = TreeNode<String>();

  void toggleExpansion(String nodePath) {
    final node = controller?.elementAt(nodePath);
    if (node != null) controller?.toggleExpansion(node);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: TreeView.simple<String>(
        key: globalKey,
        tree: tree,
        builder: (context, level, item) => ListTile(
          title: Text("Item ${item.level}-${item.key}"),
        ),
      ),
    );
  }
}
kespaldon commented 1 year ago

hi, you didn't really answer the first question

expand all child nodes

if you could respond to this that'd be great

jawwad-hassan89 commented 1 year ago

@kespaldon right now there is no builtin method to expand all the children of a node. So you will have to recursively iterate through the children, and expand them. I will add a utility method to handle expansion of all children in the next release. For the time being you can use this handy extension to achieve the same.

extension TreeControllerX<Data, Tree extends ITreeNode<Data>>
    on TreeViewController {
  /// Utility method for programmatically expanding all the child nodes. By default
  /// only the immediate children of the node will be expanded.
  /// Set [recursive] to true for expanding all the child nodes until the leaf is
  /// reached.
  void expandAllChildren(Tree node, {bool recursive = false}) {
    for (final child in node.childrenAsList) {
      toggleExpansion(child as Tree);
      if (child.childrenAsList.isNotEmpty) expandAllChildren(child);
    }
  }
}