of static method

NavigatorState of(
  1. BuildContext context, {
  2. Key? byKey,
})

Navigator's state from the closest instance of this class that encloses the given context.

Implementation

static NavigatorState of(BuildContext context, {Key? byKey}) {
  NavigatorRenderElement? parent;

  context.visitAncestorElements((element) {
    // match type
    if (element is NavigatorRenderElement) {
      // match key
      if (null == byKey || element.key == byKey) {
        parent = element;

        return false;
      }
    }

    return true;
  });

  var parentNavigator = parent;

  if (null == parentNavigator) {
    if (DEBUG_BUILD) {
      var debugService = ServicesRegistry.instance.getDebug(context);

      debugService.exception(
        '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 dummy state if user has registered their own error handler
    /// in debug service, which may not throw exception on error above.
    ///
    return NavigatorState(const Navigator(routes: []));
  }

  parentNavigator.addDependent(context);

  return parentNavigator.state;
}