of static method

GoRouterState of(
  1. BuildContext context
)

Gets the GoRouterState from context.

The returned GoRouterState will depends on which GoRoute or ShellRoute the input context is in.

This method only supports GoRoute and ShellRoute that generate ModalRoutes. This is typically the case if one uses GoRoute.builder, ShellRoute.builder, CupertinoPage, MaterialPage, CustomTransitionPage, or NoTransitionPage.

This method is fine to be called during GoRoute.builder or ShellRoute.builder.

This method cannot be called during GoRoute.pageBuilder or ShellRoute.pageBuilder since there is no GoRouterState to be associated with.

To access GoRouterState from a widget.

GoRoute(
  path: '/:id'
  builder: (_, __) => MyWidget(),
);

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('${GoRouterState.of(context).pathParameters['id']}');
  }
}

Implementation

static GoRouterState of(BuildContext context) {
  final ModalRoute<Object?>? route = ModalRoute.of(context);
  if (route == null) {
    throw GoError('There is no modal route above the current context.');
  }
  final RouteSettings settings = route.settings;
  if (settings is! Page<Object?>) {
    throw GoError(
        'The parent route must be a page route to have a GoRouterState');
  }
  final GoRouterStateRegistryScope? scope = context
      .dependOnInheritedWidgetOfExactType<GoRouterStateRegistryScope>();
  if (scope == null) {
    throw GoError(
        'There is no GoRouterStateRegistryScope above the current context.');
  }
  final GoRouterState state =
      scope.notifier!._createPageRouteAssociation(settings, route);
  return state;
}