# TreeView Custom Data

The Node class supports the use of custom data. You can use the data property on a Node instance to store data that you want to easily retrieve. The data can be any Dart object or class. One TreeView can contain nodes that store different data.

Note that when using TreeViewController methods that return an array of nodes, those nodes could each have data properties with different types and therefore those methods return Node<dynamic>. You are then responsible for performing the appropriate cast.

# Usage

When using the data property of the Node class, it is recommended that you specify the type when instantiating.

var node = Node<double>(..., data: 4.7);
var node = Node<bool>(..., data: true);
var node = Node<CustomClass>(..., data: customClass);

This ensures the actual data type is retrieved and not a dynamic. If you need to store dynamic data, just omit the type and perform the cast later in your code.

var node = Node(..., data: 4.7);
var dataValue = node.data as double;

# Example

class Person {
  final String name;
  final List<Animal> pets;

  Person({this.name, this.pets});
}

class Animal {
  final String name;

  Animal({this.name});
}

Animal otis = Animal(name: 'Otis');
Animal zorro = Animal(name: 'Zorro');
Person lukas = Person(name: 'Lukas', pets: [otis, zorro]);

List<Node> nodes = [
  Node<Person>(
    label: 'Lukas',
    key: 'lukas',
    data: lukas,
    children: [
      Node<Animal>(
        label: 'Otis',
        key: 'otis',
        data: otis,
      ),      
      //<T> is optional but recommended. If not specified, code can return Node<dynamic> instead of Node<Animal>
      Node(
        label: 'Zorro',
        key: 'zorro',
        data: zorro,
      ),
    ]
  ),
];
TreeViewController _treeViewController = TreeViewController(children: nodes);
TreeView(
  controller: _treeViewController,
  onNodeTap: (key) {
    Node selectedNode = _treeViewController.getNode(key);
    var selectedModel = selectedNode.data;
  },
),
Last Updated: 8/7/2021, 7:02:34 AM