of<T extends Object?> static method

Router<T> of<T extends Object?>(
  1. BuildContext context
)

Retrieves the immediate Router ancestor from the given context.

This method provides access to the delegates in the Router. For example, this can be used to access the backButtonDispatcher of the parent router when creating a ChildBackButtonDispatcher for a nested Router.

If no Router ancestor exists for the given context, this will assert in debug mode, and throw an exception in release mode.

See also:

  • maybeOf, which is a similar function, but it will return null instead of throwing an exception if no Router ancestor exists.

Implementation

static Router<T> of<T extends Object?>(BuildContext context) {
  final _RouterScope? scope = context.dependOnInheritedWidgetOfExactType<_RouterScope>();
  assert(() {
    if (scope == null) {
      throw FlutterError(
        'Router operation requested with a context that does not include a Router.\n'
        'The context used to retrieve the Router must be that of a widget that '
        'is a descendant of a Router widget.',
      );
    }
    return true;
  }());
  return scope!.routerState.widget as Router<T>;
}