of static method

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

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

Typical usage is as follows:

Navigator.of(context)
  ..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.

If there is no Navigator in the given context, this function will throw a FlutterError in debug mode, and an exception in release mode.

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

Implementation

static NavigatorState of(
  BuildContext context, {
  bool rootNavigator = false,
}) {
  // Handles the case where the input context is a navigator element.
  NavigatorState? navigator;
  if (context is StatefulElement && context.state is NavigatorState) {
    navigator = context.state as NavigatorState;
  }
  if (rootNavigator) {
    navigator = context.findRootAncestorStateOfType<NavigatorState>() ?? navigator;
  } else {
    navigator = navigator ?? context.findAncestorStateOfType<NavigatorState>();
  }

  assert(() {
    if (navigator == null) {
      throw FlutterError(
        'Navigator operation requested with a context that does not include a Navigator.\n'
        'The context used to push or pop routes from the Navigator must be that of a '
        'widget that is a descendant of a Navigator widget.',
      );
    }
    return true;
  }());
  return navigator!;
}