findRootAncestorStateOfType<T extends State<StatefulWidget>> method

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

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

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.


T findRootAncestorStateOfType<T extends State<StatefulWidget>>() {
  Element ancestor = _parent;
  StatefulElement statefulAncestor;
  while (ancestor != null) {
    if (ancestor is StatefulElement && ancestor.state is T)
      statefulAncestor = ancestor;
    ancestor = ancestor._parent;
  return statefulAncestor?.state as T;