rootAncestorStateOfType method

  1. @override
State<StatefulWidget> rootAncestorStateOfType (TypeMatcher matcher)

Returns the State object of the furthest ancestor StatefulWidget widget that matches the given TypeMatcher.

Functions the same way as ancestorStateOfType but keeps visiting subsequent ancestors until there are none of the type matching TypeMatcher 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.


State rootAncestorStateOfType(TypeMatcher matcher) {
  Element ancestor = _parent;
  StatefulElement statefulAncestor;
  while (ancestor != null) {
    if (ancestor is StatefulElement && matcher.check(ancestor.state))
      statefulAncestor = ancestor;
    ancestor = ancestor._parent;
  return statefulAncestor?.state;