findAncestorStateOfType<T extends State<StatefulComponent>> method

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

Returns the State object of the nearest ancestor StatefulComponent component that is an instance of the given type T.

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

Implementation

@override
T? findAncestorStateOfType<T extends State<StatefulComponent>>() {
  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?;
}