maybeOf static method

NavigatorState? maybeOf(
  1. BuildContext context, {
  2. bool rootNavigator = false,
})

The state from the closest instance of this class that encloses the given context, if any.

Typical usage is as follows:

NavigatorState? navigatorState = Navigator.maybeOf(context);
if (navigatorState != null) {
  navigatorState
    ..pop()
    ..pop()
    ..pushNamed('/settings');
}

If rootNavigator is set to true, the state from the furthest instance of this class is given instead. Useful for pushing contents above all subsequent instances of Navigator.

Will return null if there is no ancestor Navigator in the context.

This method can be expensive (it walks the element tree).

Implementation

static NavigatorState? maybeOf(
  BuildContext context, {
  bool rootNavigator = false,
}) {
  NavigatorState? navigator;
  if (context case StatefulElement(:final NavigatorState state)) {
    navigator = state;
  }

  return rootNavigator
      ? context.findRootAncestorStateOfType<NavigatorState>() ?? navigator
      : navigator ?? context.findAncestorStateOfType<NavigatorState>();
}