getIndexPath static method

Iterable<int>? getIndexPath(
  1. Node ancestor,
  2. Node child
)

Returns the sequence of child indices that walks from ancestor down to child through the scene graph.

Each entry is the index into the corresponding parent's children at that level. Useful for re-resolving a node reference on a cloned subtree (see clone).

Returns null (and prints a debug warning) if ancestor is not an actual ancestor of child.

Implementation

static Iterable<int>? getIndexPath(Node ancestor, Node child) {
  List<int> result = [];
  Node? current = child;
  while (current != null) {
    if (identical(current, ancestor)) {
      return result.reversed;
    }
    if (current._parent == null) {
      break;
    }
    result.add(current._parent!.children.indexOf(current));
    current = current._parent;
  }

  debugPrint(
    'Index path formation failed because the given ancestor was not an ancestor of the given child.',
  );
  return null;
}