of static method
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 yet.
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) {
ModalRoute<Object?>? route;
GoRouterStateRegistryScope? scope;
while (true) {
route = ModalRoute.of(context);
if (route == null) {
throw _noGoRouterStateError;
}
final RouteSettings settings = route.settings;
if (settings is Page<Object?>) {
scope = context
.dependOnInheritedWidgetOfExactType<GoRouterStateRegistryScope>();
if (scope == null) {
throw _noGoRouterStateError;
}
final GoRouterState? state = scope.notifier!
._createPageRouteAssociation(
route.settings as Page<Object?>, route);
if (state != null) {
return state;
}
}
final NavigatorState? state = Navigator.maybeOf(context);
if (state == null) {
throw _noGoRouterStateError;
}
context = state.context;
}
}