addNode<T> method

List<Node> addNode<T>(
  1. String key,
  2. Node<T> newNode, {
  3. Node? parent,
  4. int? index,
  5. InsertMode mode = InsertMode.append,
})

Adds a new node to an existing node identified by specified key. It optionally accepts an InsertMode and index. If no InsertMode is specified, it appends the new node as a child at the end. This method returns a new list with the added node.

Implementation

List<Node> addNode<T>(
  String key,
  Node<T> newNode, {
  Node? parent,
  int? index,
  InsertMode mode: InsertMode.append,
}) {
  List<Node> __children = parent == null ? this.children : parent.children;
  return __children.map((Node child) {
    if (child.key == key) {
      List<Node> _children = child.children.toList(growable: true);
      if (mode == InsertMode.prepend) {
        _children.insert(0, newNode);
      } else if (mode == InsertMode.insert) {
        _children.insert(index ?? _children.length, newNode);
      } else {
        _children.add(newNode);
      }
      return child.copyWith(children: _children);
    } else {
      return child.copyWith(
        children: addNode<T>(
          key,
          newNode,
          parent: child,
          mode: mode,
          index: index,
        ),
      );
    }
  }).toList();
}