findAncestorStateOfType<T extends State<StatefulWidget>> method

  1. @override
T? findAncestorStateOfType<T extends State<StatefulWidget>>()
override

Returns the State object of the nearest ancestor StatefulWidget widget that is an instance of the given type T.

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, dependOnInheritedWidgetOfExactType is more appropriate for such cases. This method is useful for changing the state of an ancestor widget in a one-off manner, for example, to cause an ancestor scrolling list to scroll this build context's widget into view, or to move the focus in response to user interaction.

In general, though, consider using a callback that triggers a stateful change in the ancestor rather than using the imperative style implied by this method. This will usually lead to more maintainable and reusable code since it decouples widgets from each other.

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 findAncestorStateOfType in State.didChangeDependencies.

link
ScrollableState? scrollable = context.findAncestorStateOfType<ScrollableState>();

Implementation

@override
T? findAncestorStateOfType<T extends State<StatefulWidget>>() {
  assert(_debugCheckStateIsActiveForAncestorLookup());
  Element? ancestor = _parent;
  while (ancestor != null) {
    if (ancestor is StatefulElement && ancestor.state is T) {
      break;
    }
    ancestor = ancestor._parent;
  }
  final StatefulElement? statefulAncestor = ancestor as StatefulElement?;
  return statefulAncestor?.state as T?;
}