ancestorWidgetOfExactType method

  1. @override
Widget ancestorWidgetOfExactType (Type targetType)
override

Returns the nearest ancestor widget of the given type, which must be the type of a concrete Widget subclass.

This should not be used from build methods, because the build context will not be rebuilt if the value that would be returned by this method changes. In general, inheritFromWidgetOfExactType is more useful. This method is appropriate when used in interaction event handlers (e.g. gesture callbacks), or for performing one-off tasks.

Calling this method is relatively expensive (O(N) in the depth of the tree). Only call this method if the distance from this widget to the desired ancestor is known to be small and bounded.

This method should not be called from State.deactivate or State.dispose because the widget 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 ancestorWidgetOfExactType in State.didChangeDependencies.

Implementation

@override
Widget ancestorWidgetOfExactType(Type targetType) {
  assert(_debugCheckStateIsActiveForAncestorLookup());
  Element ancestor = _parent;
  while (ancestor != null && ancestor.widget.runtimeType != targetType)
    ancestor = ancestor._parent;
  return ancestor?.widget;
}