updateNode<T> method Null safety

List<Node> updateNode<T>(
  1. String key,
  2. Node<T> newNode,
  3. {Node? parent}
)

Updates an existing node identified by specified key. This method returns a new list with the updated node.

Implementation

List<Node> updateNode<T>(String key, Node<T> newNode, {Node? parent}) {
  List<Node> _children = parent == null ? this.children : parent.children;
  return _children.map((Node child) {
    if (child.key == key) {
      return newNode;
    } else {
      if (child.isParent) {
        return child.copyWith(
          children: updateNode<T>(
            key,
            newNode,
            parent: child,
          ),
        );
      }
      return child;
    }
  }).toList();
}