findAncestorStateOfType<T extends State<StatefulWidget>> static method

T? findAncestorStateOfType<T extends State<StatefulWidget>>(
  1. BuildContext context

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

This method behaves exactly like BuildContext.findAncestorWidgetOfExactType, except it only considers State objects of the specified type T between the provided BuildContext and its closest LookupBoundary ancestor. State objects past that LookupBoundary are invisible to this method. The root of the tree is treated as an implicit lookup boundary.

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.


static T? findAncestorStateOfType<T extends State>(BuildContext context) {
  StatefulElement? target;
  context.visitAncestorElements((Element ancestor) {
    if (ancestor is StatefulElement && ancestor.state is T) {
      target = ancestor;
      return false;
    return ancestor.widget.runtimeType != LookupBoundary;
  return target?.state as T?;