Sub topic 5
Introducing StatefulShellRoute.indexedStack
This chapter assumes you can write a GoRouter with nested GoRoute objects, you know what a navigator key is, and you have seen why a plain ShellRoute loses per-tab history. Here you build the smallest working tabbed app with StatefulShellRoute.indexedStack and look at what it creates at runtime.
What the route does
StatefulShellRoute is a route that has no path of its own. It wraps a list of branches in a persistent UI, such as a Scaffold with a bottom bar. Each branch gets its own Navigator, so each tab keeps its own back stack.
StatefulShellRoute.indexedStack is a named constructor that picks the most common display strategy: all branch navigators are placed in an IndexedStack, and only the one at the current index is visible. The inactive branches stay in the widget tree, so their pages and widget state survive tab switches.
| Concern | `ShellRoute` | `StatefulShellRoute.indexedStack` |
|---|---|---|
| Navigators | One, shared by all child routes | One per branch |
| Back stack per tab | Not kept. Switching tabs replaces the page. | Kept for every branch |
| Widget state per tab | Lost when the tab changes | Kept while the branch stays loaded |
| Shell receives | A `child` widget | A `StatefulNavigationShell` |
| Tab switching | `context.go` to a location | `goBranch(index)` or `context.go` |
Use ShellRoute when the child content is a single stack and persistence does not matter, for example a persistent header around a settings flow. Use StatefulShellRoute when the user moves between parallel sections and expects to return to where they were.
A complete minimal example
The following file runs as shown with go_router added to pubspec.yaml. It uses Material 3's NavigationBar, so it needs Flutter 3.7 or later. The Home screen has a counter so you can observe state preservation.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();
final GoRouter router = GoRouter(
navigatorKey: rootNavigatorKey,
initialLocation: '/home',
routes: [
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) {
return ScaffoldWithNavBar(navigationShell: navigationShell);
},
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsScreen(),
),
],
),
],
),
],
);
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,
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 HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(child: Text('Count: $_count')),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: const Center(child: Text('Settings')),
);
}
}Increase the counter, switch to Settings, and switch back. The count is still there. With a plain ShellRoute, the HomeScreen state would have been disposed.
The three parts
The route itself
StatefulShellRoute.indexedStack takes these main arguments:
branches: a required list ofStatefulShellBranchobjects. Each one becomes a tab. Branches are covered in the next chapter.builderorpageBuilder: builds the shell UI. UsepageBuilderwhen you need a custom transition or page type for the shell.restorationScopeId: optional. Set it if you use Flutter state restoration.parentNavigatorKey: optional. It says which navigator hosts the whole shell. It defaults to the root navigator.
The shell has no path. It never matches a URL by itself. A URL matches a GoRoute inside one of the branches, and go_router then finds the branch that owns that route.
The shell widget
The builder receives a StatefulNavigationShell. This object is itself a widget, and it contains the IndexedStack of branch navigators. You place it in your layout, here as the Scaffold body. It also exposes currentIndex and goBranch. The next chapters cover both.
Place navigationShell once, and never wrap it in something that rebuilds it with a different key. Replacing it throws away every branch navigator.
The branches
Each StatefulShellBranch owns a navigator and a list of routes. The first route in the list decides the branch's default location. Here that is /home for the first branch and /settings for the second. The order of branches defines the index numbers used by currentIndex and goBranch.
What happens at runtime
When the app starts at /home, go_router matches the /home route, sees that it lives in branch 0 of the shell, and builds the shell with currentIndex set to 0. When you tap Settings, goBranch(1) changes the visible branch. The Home navigator stays alive but hidden.
An IndexedStack lays out all of its children and paints only one. Because the other children remain mounted, their State objects, scroll positions and pushed pages remain too. This is the mechanism behind tab persistence, and it has a cost: hidden branches still hold memory. A branch is normally created when first visited, so a tab the user never opens costs nothing. Check this behavior against the go_router version you use.
Constraints to know
- The initial location must belong to a branch. If
initialLocationmatches no route, you get an error page, not a tab. - Paths must be unique across the whole tree. Two branches that both declare
/listmake the location ambiguous. The router can only pick one branch for it. - Every branch needs at least one route. An empty
routeslist fails an assertion when the router is built. - Top-level routes in a branch use absolute paths that start with
/. Sub-routes use relative paths without a leading slash. - The shell does not own the URL. Each branch contributes its own location. The address bar shows the active branch's current location, so a deep link such as
/settingsopens the shell with the Settings tab selected.
Common mistakes at this stage
- Using
childas the builder's third parameter. That is theShellRoutesignature. The stateful variant passes aStatefulNavigationShell. - Forgetting to place
navigationShellin the widget tree. The bar appears, but the body is blank. - Passing
selectedIndexa value that is notnavigationShell.currentIndex. The bar then disagrees with the visible tab after a deep link or back navigation. - Expecting state to survive when a screen is built as a fresh page on each tab switch, for example by calling
context.gowith a different location every time. UsegoBranchfor ordinary tab taps.
Exercise
You add a third tab to the example by adding a third StatefulShellBranch with a route at /home, the same path as the first tab. What goes wrong, and how do you fix it?
Show answer
Paths must be unique across the whole route tree. With two routes at /home, go_router cannot tell which branch owns that location. It will resolve it to one branch, and the other tab will not be reachable by its location. Give the new route its own path, such as /profile, and add a matching NavigationDestination so the bar's destination order matches the branch order.
Exercise
In ScaffoldWithNavBar, why is navigationShell.currentIndex passed to selectedIndex instead of a setState variable held in the widget?
Show answer
The current branch can change without a tap on the bar, for example through a deep link, context.go, or the system back button. currentIndex always reflects the router's actual state, so the bar stays correct. A local variable would drift out of sync and would also make the widget stateful for no reason.