Sub topic 12
Bottom navigation that keeps state with StatefulShellRoute
This chapter assumes you can define GoRoute trees, use nested routes, and call context.go and context.push. It also assumes you know what a Navigator is and that a ShellRoute wraps child routes in a shared layout.
The problem a plain ShellRoute leaves open
A ShellRoute gives you one persistent bottom bar around a single shared navigator. When the user taps another tab, go replaces the stack. The page the user was reading in the first tab is discarded, along with its scroll position and any state held in its widgets.
Most apps want what native apps do. Each tab keeps its own history, and returning to a tab restores it as it was. StatefulShellRoute provides this by giving every tab its own Navigator.
How it works internally
StatefulShellRoute.indexedStack takes a list of StatefulShellBranch objects. Each branch owns a separate navigator with its own back stack. The shell's builder receives a StatefulNavigationShell, which is both a widget and a controller. As a widget, it renders the branch navigators inside an IndexedStack. As a controller, it exposes currentIndex and goBranch.
Two details follow from this design:
- A branch is built the first time the user visits it. After that, the
IndexedStackkeeps it alive while hiding it. - The widgets in a hidden branch stay mounted, so their
Stateobjects survive.
A complete example
The app below has two tabs. The Feed tab has a counter held in a StatefulWidget and a nested post page. The Settings tab is a simple page. Run it, increment the counter, open a post, switch tabs, and switch back.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GlobalKey<NavigatorState> rootKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GoRouter router = GoRouter(
navigatorKey: rootKey,
initialLocation: '/feed',
routes: <RouteBase>[
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) =>
ScaffoldWithNavBar(navigationShell: navigationShell),
branches: <StatefulShellBranch>[
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: '/feed',
builder: (context, state) => const FeedScreen(),
routes: <RouteBase>[
GoRoute(
path: 'post/:id',
builder: (context, state) =>
PostScreen(id: state.pathParameters['id']!),
routes: <RouteBase>[
GoRoute(
path: 'photo',
// Shown above the navigation bar, not inside the branch.
parentNavigatorKey: rootKey,
builder: (context, state) => const Scaffold(
body: Center(child: Text('Full-screen photo')),
),
),
],
),
],
),
],
),
StatefulShellBranch(
routes: <RouteBase>[
GoRoute(
path: '/settings',
builder: (context, state) =>
const Center(child: Text('Settings')),
),
],
),
],
),
],
);
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: router);
}
}
class ScaffoldWithNavBar extends StatelessWidget {
const ScaffoldWithNavBar({super.key, required this.navigationShell});
final StatefulNavigationShell navigationShell;
@override
Widget build(BuildContext context) {
return Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
onDestinationSelected: (index) => navigationShell.goBranch(
index,
initialLocation: index == navigationShell.currentIndex,
),
destinations: const [
NavigationDestination(icon: Icon(Icons.list), label: 'Feed'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
),
);
}
}
class FeedScreen extends StatefulWidget {
const FeedScreen({super.key});
@override
State<FeedScreen> createState() => _FeedScreenState();
}
class _FeedScreenState extends State<FeedScreen> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Feed')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Count: $_count'),
ElevatedButton(
onPressed: () => setState(() => _count++),
child: const Text('Increment'),
),
ElevatedButton(
onPressed: () => context.go('/feed/post/7'),
child: const Text('Open post 7'),
),
],
),
),
);
}
}
class PostScreen extends StatelessWidget {
const PostScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Post $id')),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/feed/post/$id/photo'),
child: const Text('Open photo'),
),
),
);
}
}The count survives a trip to Settings. So does the open post page. The nav bar disappears over the photo page because that route sets parentNavigatorKey to the root navigator.
goBranch and the initialLocation flag
goBranch(index) makes the branch at index visible and restores its last location. It does not rebuild the branch.
The initialLocation argument controls what happens when the user taps the tab that is already selected. When it is true, the branch resets to its first route. This matches the common "tap the active tab to return to its root" behavior. The example passes index == navigationShell.currentIndex to get exactly that.
The shell is not a navigation method you call from outside. To open a route that lives in another branch, use context.go('/settings'). go_router finds the branch that owns the route and switches to it.
Branch options
StatefulShellBranch has a few useful parameters:
| Parameter | Purpose |
|---|---|
| `navigatorKey` | Lets you reach this branch's `NavigatorState` directly. |
| `initialLocation` | Overrides the location used when the branch is first shown or reset. |
| `restorationScopeId` | Enables state restoration for the branch's navigator. |
| `observers` | Attaches `NavigatorObserver`s to this branch only. |
By default, the initial location of a branch is the path of its first GoRoute. If that route needs path parameters, go_router cannot build a default location, so you must set initialLocation yourself.
Choosing a shell variant
| Variant | Behavior |
|---|---|
| `ShellRoute` | One shared navigator. Switching tabs discards the previous page. |
| `StatefulShellRoute.indexedStack` | One navigator per branch inside an `IndexedStack`. Visited branches stay alive. |
| `StatefulShellRoute` with `navigatorContainerBuilder` | You decide how the branch navigators are laid out, for example in a `PageView` or with lazy disposal. |
Common errors and gotchas
- Memory.
indexedStackkeeps every visited branch mounted. An app with many heavy tabs holds all of them. UsenavigatorContainerBuilderif you need to dispose hidden branches. - Back button. The system back button pops within the current branch. At a branch's root page, it does not switch to another tab by default. If you want that, handle it yourself with a
PopScopearound the shell. - Redirects and tabs. A top-level
redirectstill runs whengoBranchchanges location, so auth guards keep working across tabs. - Wrong key type.
navigatorKeyandparentNavigatorKeyneed aGlobalKey<NavigatorState>. A plainGlobalKeyfails type checks. - Rebuilding the shell. The shell's
builderruns again on every navigation inside any branch. Keep it cheap and read onlycurrentIndexthere.
Exercises
Exercise
A user increments a counter on the Feed tab, switches to Settings, and returns to find the counter reset to zero. The router uses a plain ShellRoute. What change restores the counter, and why does it work?
Show answer
Replace ShellRoute with StatefulShellRoute.indexedStack and put the Feed and Settings routes in separate StatefulShellBranch objects. Each branch gets its own Navigator inside an IndexedStack, so the Feed page's State object stays mounted while the Settings branch is visible, and the counter keeps its value.
Exercise
Write the onDestinationSelected callback so that tapping a tab switches to it, and tapping the tab that is already selected returns it to its first route.
Show answer
onDestinationSelected: (index) => navigationShell.goBranch(index, initialLocation: index == navigationShell.currentIndex),
Exercise
A post detail page inside the Feed branch must hide the bottom navigation bar and cover the whole screen. Which route parameter achieves this, and what must you create first?
Show answer
Set parentNavigatorKey on that GoRoute to the root navigator's key. You must first create a GlobalKey<NavigatorState> and pass it to GoRouter as navigatorKey, so the route can be placed on the root navigator instead of the branch navigator.