add<T extends Node> method

T add<T extends Node>(
  1. T node
)

Adds node to this node. The node is returned.

Nodes cannot be added to themselves or their descendants. Adding a child to its current parent is a no-op, and cancels its pending removal, so a child held on the instance survives the reload that discarded it.

Called from this node's own build, the child is additionally recorded as declared, so the next rebuild discards it before running the body again.

Implementation

T add<T extends Node>(T node) {
  if (identical(this, node)) {
    throw StateError('Cannot add a node to itself.');
  }

  if (cycles(node)) {
    throw StateError('Cannot add a node to its descendant.');
  }

  if (identical(_building, this)) {
    (_declared ??= []).add(node);
  }

  if (owns(node)) {
    node._pendingRemoval = false;
    return node;
  }

  // A move: release from the old parent without unmounting.
  node._pendingParent = null;

  if (node.hasParent) {
    node._parent!._release(node);
    node._forgetAncestry();
  }

  if (isMounted) {
    node._pendingParent = this;
    scene._tree._add(node, this);
  } else {
    _own(node);
  }

  return node;
}