Sub topic 3
Navigator keys and the root navigator
This chapter assumes you know basic gorouter usage (GoRouter, GoRoute, context.go) and the Flutter Navigator widget. It explains what a navigator key is, why gorouter has a root navigator, and how keys decide where a route is drawn. Later chapters on StatefulShellRoute depend on this model.
Why navigator keys matter
Flutter draws pages with a Navigator widget. A Navigator holds a stack of pages, and the topmost page is the one on screen. An app can contain several navigators at the same time, nested inside each other.
go_router normally creates one navigator for you. As soon as you add a shell route, there is more than one. A tab bar needs its own navigator for the tab content, and the app still needs an outer navigator to show full-screen pages over everything.
A GlobalKey<NavigatorState> is how you name a navigator. With a key you can:
- tell go_router which navigator should display a given route,
- reach the
NavigatorStateof a navigator directly, if you ever need to.
The root navigator
The root navigator is the outermost Navigator in the app. GoRouter creates it for you. Every route that is not inside a shell is displayed by it.
You can supply your own key for it with the navigatorKey parameter of GoRouter:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GlobalKey<NavigatorState> rootNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GoRouter router = GoRouter(
navigatorKey: rootNavigatorKey,
initialLocation: '/home',
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const Scaffold(
body: Center(child: Text('Home')),
),
),
],
);If you leave navigatorKey out, go_router creates a key internally and the app works as before. You only need to pass one when other code must refer to the root navigator. In the next chapters, that is the case when a route inside a tab must be shown above the tab bar.
The debugLabel argument is optional. It makes the key readable in error messages and in the widget inspector, which helps later when you have several keys.
Where keys appear in go_router
Three classes accept a navigator key. Each one means something different.
| Where | Parameter | Meaning |
|---|---|---|
| `GoRouter` | `navigatorKey` | The key of the root navigator. |
| `ShellRoute` and `StatefulShellBranch` | `navigatorKey` | The key of the navigator that the shell or branch creates for its child routes. |
| `GoRoute` | `parentNavigatorKey` | The navigator on which this route must be displayed. |
The first two name a navigator that is being created. The third points at a navigator that already exists. Keeping this difference in mind avoids most key mistakes.
How a route chooses its navigator
Without any key, a route is displayed by the navigator of the closest enclosing shell, or by the root navigator if it has no shell around it. That is the default, and it is usually what you want.
Setting parentNavigatorKey on a GoRoute overrides the default. go_router then places the page on the navigator with that key.
flowchart TDThe diagram below shows the structure that results when a shell exists.
The solid lines show where pages live by default. The dotted line shows a route that opts out of the shell and is drawn by the root navigator.
Declaring a key for a shell navigator
A shell route owns an inner navigator. You can give that navigator a key of its own:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GlobalKey<NavigatorState> rootNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> shellNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'shell');
final GoRouter router = GoRouter(
navigatorKey: rootNavigatorKey,
initialLocation: '/home',
routes: [
ShellRoute(
navigatorKey: shellNavigatorKey,
builder: (context, state, child) {
return Scaffold(
body: child,
bottomNavigationBar: const SizedBox(height: 56),
);
},
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const Center(child: Text('Home')),
routes: [
GoRoute(
path: 'photo',
parentNavigatorKey: rootNavigatorKey,
builder: (context, state) =>
const Scaffold(body: Center(child: Text('Photo'))),
),
],
),
],
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));Here /home is drawn inside the shell, with the bottom bar visible. /home/photo has parentNavigatorKey: rootNavigatorKey, so it covers the whole screen, bar included. The URL is still /home/photo, and the route is still a child of /home in the tree. Only the place where it is drawn changes.
For a plain ShellRoute, the shell key is optional. go_router creates one when you omit it. You provide it when a route needs to target the shell navigator explicitly.
For StatefulShellBranch, the same rule applies: each branch gets its own navigator, and you can name it with navigatorKey. Chapter material on branches covers this in detail.
Rules the keys must follow
go_router checks key usage in debug mode and throws assertion errors when the setup is inconsistent. These are the rules to remember.
- Use one key per navigator. Two shells or branches that share a key are a mistake, because one
GlobalKeycan only be attached to one widget at a time. - Create keys once. Define them as top-level or long-lived
finalfields. Creating aGlobalKeyinside abuildmethod produces a new key on every rebuild, and the navigator loses its state. - Point
parentNavigatorKeyat an ancestor. A route can only target the root navigator or a navigator of a shell that encloses it. Pointing at an unrelated navigator is invalid. - Pass the same root key to
GoRouter. If you userootNavigatorKeyas aparentNavigatorKey, it must be the object you gave toGoRouter(navigatorKey: ...). A different key matches nothing.
Effects on navigation behavior
Choosing a navigator changes behavior beyond appearance.
- Back button and
pop. Popping removes the topmost page of the navigator that shows it. A route on the root navigator pops back to the page beneath it on the root navigator, which reveals the shell again. - Visible chrome. Pages on the shell navigator appear inside the shell widget, so the tab bar and app bar stay. Pages on the root navigator replace the whole screen.
- Transitions. Each navigator animates its own pages. A root route slides over the full screen, and a shell route animates only inside the shell body.
context.pushandcontext.go. Both resolve the target route and use its navigator, so you do not pass the key at the call site. The route definition decides.
Reading the root navigator at runtime
You rarely need the key outside the route definitions. When you do, for example to show a dialog from code that has no BuildContext, the key gives you a context on the root navigator:
import 'package:flutter/material.dart';
import 'router_keys.dart';
Future<void> showSessionExpiredDialog() async {
final context = rootNavigatorKey.currentContext;
if (context == null) {
return;
}
await showDialog<void>(
context: context,
builder: (context) => const AlertDialog(
title: Text('Session expired'),
content: Text('Please sign in again.'),
),
);
}currentContext is null until the navigator has been built, so the check is required. Dialogs shown with the root context cover the whole app, including any shell.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| A page that should be full screen still shows the tab bar. | `parentNavigatorKey` is missing on the route. | Add `parentNavigatorKey: rootNavigatorKey`. |
| Assertion about a duplicate `GlobalKey`. | Two navigators were given the same key. | Create one key per shell or branch. |
| A shell resets its state on every rebuild. | The key is created inside `build`. | Move it to a top-level `final`. |
| Assertion that the parent navigator key is not found. | The key does not match any ancestor navigator. | Pass the same root key to `GoRouter` and the route. |
| `rootNavigatorKey.currentContext` is `null`. | Called before the first frame, or the key was never passed to `GoRouter`. | Pass the key to `GoRouter` and call after startup. |
Exercise
A route /home/photo is nested under /home, which lives in a ShellRoute with a bottom bar. You want the photo page to hide the bar. Which parameter do you set, on which class, and with which value? What does the URL look like afterward?
Show answer
Set parentNavigatorKey: rootNavigatorKey on the GoRoute for photo, where rootNavigatorKey is the same key object passed as navigatorKey to GoRouter. The URL stays /home/photo, because the key changes only which navigator draws the page, not the route tree or the path.
Exercise
A teammate writes final key = GlobalKey<NavigatorState>(); inside a widget's build method and passes it to a ShellRoute. What goes wrong, and how do you fix it?
Show answer
Each rebuild creates a new key, so Flutter treats the navigator as a different one and discards its page stack and state. Move the key to a top-level final (or another long-lived field) so the same object is reused for the life of the router.