addNode method

List<Node<T>> addNode(
  1. String key,
  2. Node<T> newNode, {
  3. Node<T>? 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<T>> addNode(
  String key,
  Node<T> newNode, {
  Node<T>? parent,
  int? index,
  InsertMode mode = InsertMode.append,
}) {
  List<Node<T>> _children = parent == null ? this.children : parent.children;
  return _children.map((Node<T> child) {
    if (child.key == key) {
      List<Node<T>> _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(
          key,
          newNode,
          parent: child,
          mode: mode,
          index: index,
        ),
      );
    }
  }).toList();
}