Sub topic 9
How each tab keeps its own stack and state
This chapter explains the mechanism behind per-tab history in StatefulShellRoute.indexedStack: what is stored, where it lives, and when it is lost. It assumes you can already build a basic shell with branches and a NavigationBar as in the earlier chapters. It also assumes you know that a Flutter Navigator holds a stack of pages and that a State object lives as long as its widget stays mounted.
One navigator per branch
A plain ShellRoute creates one nested Navigator that is shared by every route inside it. Switching "tabs" with context.go replaces whatever that navigator is showing, so the old tab's history is gone.
StatefulShellRoute creates one Navigator for each StatefulShellBranch. Each of these navigators has its own page stack. The indexedStack variant keeps all of them in a Flutter IndexedStack. Only the branch at currentIndex is visible and interactive, and the others stay in the widget tree.
Two consequences follow from this design:
- Navigation history survives because each branch's stack lives inside its own
Navigatorand is never popped when you leave the tab. - Widget state survives because the pages in a hidden branch are still mounted. Their
Stateobjects, scroll controllers, text controllers and animation controllers are not disposed.
Branch navigators are built lazily
go_router does not build every branch up front. A branch's navigator is created the first time that branch becomes active. Before that, the branch only has a placeholder in the IndexedStack. Once built, it stays mounted for as long as the shell exists.
This matters in two ways. First, a screen in a tab you have never opened has not run initState yet. Second, any code that assumes all tabs are live (for example, reading a controller that a hidden tab creates) can fail on a cold start.
What goBranch restores
StatefulNavigationShell.goBranch(index) does not rebuild the branch from scratch. The shell remembers the last location for each branch, and goBranch navigates to that remembered location. The branch navigator already holds the matching pages, so the user lands exactly where they left.
The initialLocation argument changes this behavior:
initialLocation: false(the default) restores the branch's last location.initialLocation: truenavigates to the branch's initial location instead. The branch's own stack is reset to that location.
The ScaffoldWithNavBar from the earlier chapter passes index == navigationShell.currentIndex. That gives the common behavior where tapping a different tab restores it, and tapping the active tab returns it to its root.
A branch's initial location is its initialLocation property if you set one. Otherwise gorouter uses the path of the first GoRoute in the branch. That path must not contain required parameters, such as :id, or gorouter cannot resolve it. In that case set initialLocation explicitly.
A runnable demonstration
The app below puts a counter in each tab's root screen and gives each tab a details page. Increment a counter, open details, switch tabs, then switch back. The counter value and the details page are both still there.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const App());
final GoRouter _router = GoRouter(
initialLocation: '/home',
routes: [
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) =>
AppShell(navigationShell: navigationShell),
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) =>
const CounterScreen(title: 'Home', detailsPath: '/home/details'),
routes: [
GoRoute(
path: 'details',
builder: (context, state) =>
const DetailsScreen(title: 'Home details'),
),
],
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/settings',
builder: (context, state) => const CounterScreen(
title: 'Settings', detailsPath: '/settings/details'),
routes: [
GoRoute(
path: 'details',
builder: (context, state) =>
const DetailsScreen(title: 'Settings details'),
),
],
),
],
),
],
),
],
);
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) =>
MaterialApp.router(routerConfig: _router);
}
class AppShell extends StatelessWidget {
const AppShell({super.key, required this.navigationShell});
final StatefulNavigationShell navigationShell;
@override
Widget build(BuildContext context) {
return 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,
),
),
);
}
}
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key, required this.title, required this.detailsPath});
final String title;
final String detailsPath;
@override
State<CounterScreen> createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Count: $_count'),
FilledButton(
onPressed: () => setState(() => _count++),
child: const Text('Increment'),
),
TextButton(
onPressed: () => context.go(widget.detailsPath),
child: const Text('Open details'),
),
],
),
),
);
}
}
class DetailsScreen extends StatelessWidget {
const DetailsScreen({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(child: Text(title)),
);
}
}Run it and try this sequence: increment Home to 3, open Home details, tap Settings, increment it to 1, then tap Home. You land on Home details. Press back and Home still shows Count: 3. Tap the active Home tab and you return to its root screen, and the counter is still 3 because the root screen was never disposed.
What is kept and what is lost
| Situation | Navigation stack | Widget `State` |
|---|---|---|
| Switch to another tab and back | Kept | Kept |
| Tap the active tab with `initialLocation: true` | Reset to the branch's initial location | Pages above the root are disposed. The root page's `State` is kept. |
| Pop a page inside the branch | Page removed | That page's `State` is disposed |
| Branch never opened | Not built yet | Not created yet |
| Hot restart or app restart | Lost unless you use state restoration | Lost |
| `GoRouter` object recreated (for example, built inside a `build` method) | Lost | Lost |
The last row is a frequent source of "my tabs forget everything" bugs. The state lives in objects owned by the router, so a new GoRouter starts empty.
Using context.go across branches
context.go('/home/details') called while another tab is active does two things. It makes the Home branch the active one, and it sets that branch's stack to the pages that match the new location. This replaces whatever the Home stack held before. If a user had Home at /home/details and you call context.go('/home'), the details page is removed from the Home stack.
Use goBranch when you want to restore a tab as the user left it. Use context.go when you want to jump to a specific location and accept that the target branch's stack is rewritten.
Keeping state that is not widget state
Widget state survives tab switches, but some state does not belong in widgets:
- Data shared across tabs (the signed-in user, a shopping cart) belongs in a provider, repository or other app-level object, not in a tab's
State. - Per-tab state that must survive an app restart needs Flutter's restoration APIs. Set
restorationScopeIdonStatefulShellBranchand on theGoRouter, and useRestorationMixinin the screens that need it. - Scroll positions are kept automatically in a hidden branch, because the
Scrollablestays mounted. APageStorageKeyis only needed for lists that you rebuild yourself.
Debugging lost state
If a tab loses its history or state, check these in order:
- Is the
GoRoutercreated once, outsidebuild, or held in aStatefield? - Does the shell's
builderreturnnavigationShellas the body? Wrapping it in a widget with a changingkeyrebuilds the whole subtree. - Are you calling
context.gowhere you meantgoBranch? - Is
initialLocation: truepassed on every tap rather than only on the active tab? - Did you swap
indexedStackfor a customnavigatorContainerBuilderthat only builds the current child? Such a container disposes hidden branches, so their state is lost.
Exercise
In the demo app, a user opens Home details, switches to Settings, and then your code calls context.go('/home'). What does the Home tab show afterward, and what would you call instead to bring the user back to Home details?
Show answer
The Home tab shows its root screen. context.go('/home') makes Home active and rewrites the Home stack to the matched location, so the details page is removed and disposed. To restore the tab as the user left it, call navigationShell.goBranch(0) with initialLocation left as false.
Exercise
A teammate reports that the counter on the Home root screen resets to 0 every time the user taps the Home tab while Home is already selected. Is that a bug, and which argument controls it?
Show answer
It is expected behavior, not a bug in go_router. The tap handler passes initialLocation: index == navigationShell.currentIndex, so tapping the active tab resets the branch to its initial location. The counter itself should survive if the root screen stays mounted. If it resets, check whether the root route's page was rebuilt with a new key. To disable the reset, pass initialLocation: false.