visitAncestorElements method Null safety

  1. @override
void visitAncestorElements(
  1. bool visitor(
    1. Element element
    )
)
override

Walks the ancestor chain, starting with the parent of this build context's widget, invoking the argument for each ancestor. The callback is given a reference to the ancestor widget's corresponding Element object. The walk stops when it reaches the root widget or when the callback returns false. The callback must not return null.

This is useful for inspecting the widget tree.

Calling this method is relatively expensive (O(N) in the depth of the tree).

This method should not be called from State.deactivate or State.dispose because the element tree is no longer stable at that time. To refer to an ancestor from one of those methods, save a reference to the ancestor by calling visitAncestorElements in State.didChangeDependencies.

Implementation

@override
void visitAncestorElements(bool Function(Element element) visitor) {
  assert(_debugCheckStateIsActiveForAncestorLookup());
  Element? ancestor = _parent;
  while (ancestor != null && visitor(ancestor)) {
    ancestor = ancestor._parent;
  }
}