Sub topic 14
Pitfalls and Debugging Tips
This chapter assumes you have built a tabbed app with StatefulShellRoute.indexedStack. It assumes you know StatefulShellBranch, StatefulNavigationShell.goBranch, nested detail routes, and parentNavigatorKey. It collects the mistakes that cost the most time and gives a repeatable way to find them.
How shell routing fails
Most shell bugs fall into four groups. Each group has a distinct symptom, so the symptom tells you where to look first.
Pitfall 1: Path mistakes
go_router checks the route tree when you build the GoRouter, so path mistakes show up as assertions at startup.
- Leading slash on a sub-route. A top-level route needs a leading
/. A nested route must not have one. Writepath: 'details/:id'under/home, notpath: '/details/:id'. The full location is then/home/details/42. - Duplicate full paths. Two routes in different branches can resolve to the same full path, for example
/listin both Home and Search. The router matches the first one it finds. The second branch then shows the wrong screen, or you get a duplicate-path error. Give each branch a distinct prefix such as/home/...and/search/.... - Path parameters at the start of a branch. A branch needs a starting location. By default it uses the first route's path. A path like
/profile/:idhas no concrete value to start from. SetinitialLocationon the branch.
StatefulShellBranch(
initialLocation: '/profile/me',
routes: [
GoRoute(
path: '/profile/:id',
builder: (context, state) =>
Text('Profile ${state.pathParameters['id']}'),
),
],
)Pitfall 2: Navigator keys
Every shell branch owns a navigator. A full-screen route has to be attached to an ancestor navigator, and the key is how you name it.
| Symptom | Likely cause | Fix |
|---|---|---|
| A "full-screen" page still shows the tab bar | The route is nested in a branch with no `parentNavigatorKey` | Set `parentNavigatorKey: rootNavigatorKey` on that route |
| Assertion about a navigator key at startup | The key given to a route was never passed to `GoRouter(navigatorKey: ...)`, or it is not an ancestor of that route | Pass the same `GlobalKey<NavigatorState>` instance to both places |
| Keys differ between hot reloads | The key is created inside `build` | Create keys once, as top-level `final` values or static fields |
| `Navigator.of(context).push` covers the tab bar | The shell widget's context sits above the branch navigators, so it finds the root navigator | Use `context.push` from go_router, or call it from a screen inside the branch |
A related point is which context you use. Inside a branch screen, Navigator.of(context) finds that branch's navigator. Inside the shell widget (ScaffoldWithNavBar), the same call finds the root navigator. Mixing go_router calls and raw Navigator calls is a common source of confusing stacks. Pick one style per app.
Pitfall 3: Unexpected state loss
Tab state is kept only if the branch navigators stay alive in the widget tree. Several mistakes break that.
- Using
ShellRoutefor tabs. A plainShellRoutehas one navigator. Switching tabs replaces the page, so the old tab's stack and widget state are discarded. Tabs that must remember their history needStatefulShellRoute. - Navigating with
context.goinstead ofgoBranch.goBranchreturns to the location the branch was last at.context.go('/home')navigates to exactly that location, so a detail page the user had open in Home is replaced by the Home root. UsegoBranchfor tab buttons. Usegowhen you do want to land on a specific page. - Passing the wrong
initialLocationflag. The codeinitialLocation: index == navigationShell.currentIndexresets the tab only when the active tab is tapped again. Passingtruealways would wipe every tab's stack on each switch. - A custom container that drops children. With
navigatorContainerBuilder, showing onlychildren[currentIndex]removes the other navigators from the tree and disposes them. Keep all children mounted and hide the inactive ones, for example withOffstageorIndexedStack. - Rebuilding the shell with a changing key. If you give the shell widget or the
NavigationShella newKeyon each build, Flutter treats it as a new widget and rebuilds everything below it. - Expecting every tab to start at launch. Branches are built when first needed, so do not rely on a tab's
initStatehaving run before the user visits it. Put shared data in a provider or repository above the router.
Widget-level state inside a screen, such as scroll position or text input, survives only while that screen stays in its branch's stack. A screen that is popped is gone, so its state is gone too. If you need it back, store it outside the widget.
Pitfall 4: Redirects
A redirect runs on every navigation, including ones that happen inside branches. Two rules prevent most trouble.
- Return
nullwhen nothing needs to change. A redirect that always returns a location sends the router in a circle. go_router stops afterredirectLimitredirects (5 by default) and shows an error page. - Make the router re-check on state changes. A redirect reads auth state when navigation happens. If the user logs out while sitting on a page, nothing re-runs the redirect unless you pass a
ListenableasrefreshListenable.
The next program is complete and runnable. It combines a guard, logging, and a minimal shell. It shows the symmetrical redirect conditions that avoid loops.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GlobalKey<NavigatorState> rootNavigatorKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final ValueNotifier<bool> loggedIn = ValueNotifier<bool>(false);
final GoRouter router = GoRouter(
navigatorKey: rootNavigatorKey,
initialLocation: '/home',
debugLogDiagnostics: true,
refreshListenable: loggedIn,
redirect: (context, state) {
final atLogin = state.matchedLocation == '/login';
if (!loggedIn.value && !atLogin) return '/login';
if (loggedIn.value && atLogin) return '/home';
return null;
},
routes: [
GoRoute(
path: '/login',
builder: (context, state) => Scaffold(
body: Center(
child: FilledButton(
onPressed: () => loggedIn.value = true,
child: const Text('Log in'),
),
),
),
),
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) => Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
onDestinationSelected: (index) => navigationShell.goBranch(
index,
initialLocation: index == navigationShell.currentIndex,
),
),
),
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const Center(child: Text('Home')),
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/settings',
builder: (context, state) => Center(
child: FilledButton(
onPressed: () => loggedIn.value = false,
child: const Text('Log out'),
),
),
),
],
),
],
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));Pressing "Log out" changes loggedIn. Because of refreshListenable, the redirect runs again and moves the user to /login, even though no navigation call was made.
Debugging tools
Start with the log. debugLogDiagnostics: true prints each navigation, the matched routes, and every redirect in the console. Read it from the top after a failure. The first unexpected line is usually the cause.
Then inspect the location the router thinks it is at. These values from GoRouterState answer different questions.
| Property | What it tells you |
|---|---|
| `state.uri` | The full requested location, including the query string |
| `state.matchedLocation` | The location that matched, without the query string. Use it in redirects |
| `state.fullPath` | The route template, for example `/home/details/:id`. Use it to see which route matched |
| `state.pathParameters` | The values captured from `:name` segments |
Inside a widget, GoRouterState.of(context) returns the state for that screen. To check the overall stack, print router.routerDelegate.currentConfiguration.uri after an action.
Two further habits help. Give keys a debugLabel, as shown above, so error messages name the navigator. When a bug is hard to see, remove the shell and reproduce it with two plain routes. Then add the shell back to see which layer introduces it.
Quick reference
- Sub-route paths have no leading slash. Full paths must be unique across all branches.
- A branch whose first route has path parameters needs
initialLocation. - Pass the root key to
GoRouter(navigatorKey: ...)and toparentNavigatorKeyon routes that cover the shell. - Use
goBranchfor tab buttons. Reset a tab only when its own button is tapped again. - Keep every branch navigator mounted in a custom container.
- Return
nullfromredirectwhen no change is needed, and addrefreshListenablefor auth changes. - Turn on
debugLogDiagnosticsfirst, then comparematchedLocationandfullPath.
Exercise
A user opens a detail page inside the Home tab, switches to Settings, then taps Home. The detail page is gone and Home shows its root screen. The tab button calls navigationShell.goBranch(index, initialLocation: true). What is wrong, and what is the fix?
Show answer
Passing initialLocation: true on every tap tells go_router to reset the target branch to its initial location, so Home loses its stack on each switch. Use initialLocation: index == navigationShell.currentIndex, which resets a branch only when its active tab is tapped again.
Exercise
You add a /photo route under /home for a full-screen viewer, but the bottom bar stays visible. You also see that the router builds without errors. Name the cause and write the one line that fixes it.
Show answer
The route has no parentNavigatorKey, so it opens in the Home branch's own navigator, which sits inside the shell. Add parentNavigatorKey: rootNavigatorKey to the /photo GoRoute, using the same key that was passed to GoRouter(navigatorKey: ...). The viewer then opens on the root navigator and covers the tab bar.