findRootAncestorStateOfType<T extends State<StatefulWidget>> static method

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

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

This method behaves exactly like BuildContext.findRootAncestorStateOfType, except it considers the closest LookupBoundary ancestor of context to be the root. State objects past that LookupBoundary are invisible to this method. The root of the tree is treated as an implicit lookup boundary.

Functions the same way as findAncestorStateOfType but keeps visiting subsequent ancestors until there are none of the type instance of T remaining. Then returns the last one found.

This operation is O(N) as well though N is the entire widget tree rather than a subtree.

Implementation

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