Sub topic 14
Persistent bottom navigation with ShellRoute
This chapter assumes you have read the earlier chapters on go_router setup and path parameters. You should know how GoRoute, context.go, and context.push work, and what a Navigator is.
Many apps keep a bottom navigation bar on screen while the content above it changes. With a plain GoRoute list, every route builds its own Scaffold. Each tab change would then replace the whole screen, including the bar. ShellRoute solves this by wrapping a group of routes in a shared UI frame.
How a shell works
A ShellRoute creates a second, nested Navigator. Routes listed under the shell are shown inside that inner Navigator. The shell's builder receives that navigator as a child widget and places it wherever you like, usually in the body of a Scaffold that also has a NavigationBar.
Two consequences follow from this structure:
- The shell widget is not rebuilt from scratch when you move between its child routes. Only the
childchanges, so the navigation bar stays in place. - A route is displayed in the navigator of the nearest shell above it. To show a route over the whole shell, hiding the bar, you must tell it to use the root navigator.
A complete example
The following app has three tabs and a detail route nested under Home. It also has a Settings route that covers the bar.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const MyApp());
final GlobalKey<NavigatorState> _rootKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> _shellKey =
GlobalKey<NavigatorState>(debugLabel: 'shell');
final GoRouter _router = GoRouter(
navigatorKey: _rootKey,
initialLocation: '/home',
routes: [
ShellRoute(
navigatorKey: _shellKey,
builder: (context, state, child) =>
AppShell(location: state.uri.path, child: child),
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeTab(),
routes: [
GoRoute(
path: 'item/:id',
builder: (context, state) =>
ItemScreen(id: state.pathParameters['id']!),
),
],
),
GoRoute(
path: '/search',
builder: (context, state) =>
const Center(child: Text('Search')),
),
GoRoute(
path: '/profile',
builder: (context, state) => Center(
child: ElevatedButton(
onPressed: () => context.push('/settings'),
child: const Text('Open settings'),
),
),
),
],
),
GoRoute(
path: '/settings',
parentNavigatorKey: _rootKey,
builder: (context, state) => Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: const Center(child: Text('No bottom bar here')),
),
),
],
);
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: _router);
}
}
class AppShell extends StatelessWidget {
const AppShell({super.key, required this.location, required this.child});
final String location;
final Widget child;
static const _tabs = ['/home', '/search', '/profile'];
int get _index {
final i = _tabs.indexWhere(location.startsWith);
return i < 0 ? 0 : i;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: child,
bottomNavigationBar: NavigationBar(
selectedIndex: _index,
onDestinationSelected: (i) => context.go(_tabs[i]),
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.search), label: 'Search'),
NavigationDestination(icon: Icon(Icons.person), label: 'Profile'),
],
),
);
}
}
class HomeTab extends StatelessWidget {
const HomeTab({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () => context.go('/home/item/7'),
child: const Text('Open item 7'),
),
);
}
}
class ItemScreen extends StatelessWidget {
const ItemScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Item $id')),
body: Center(child: Text('Details for $id')),
);
}
}What each part does
navigatorKeyonGoRouternames the root navigator.navigatorKeyonShellRoutenames the inner one. You only need the shell key if you refer to it elsewhere, but keeping both makes intent clear.- The shell
builderhas three parameters:context,state, andchild. Thestatedescribes the current location, so the shell can highlight the right tab. _indexusesstartsWith, so/home/item/7still selects the Home tab.parentNavigatorKey: _rootKeyon/settingsmakes it appear on the root navigator, above the shell.
Note that /settings is declared outside the shell. The parentNavigatorKey is what sets the display target, but declaring it as a sibling keeps the route tree honest about where the page lives.
The limitation of ShellRoute: tab state
context.go('/search') replaces the current location. If you were three screens deep in Home and switch to Search and back, the Home stack is gone. The inner navigator held only one branch at a time, so the old pages were disposed. Scroll positions and text field contents are lost too.
Most mobile users expect each tab to remember where they were. StatefulShellRoute.indexedStack provides that. It keeps one navigator per branch and shows them through an IndexedStack, so inactive branches stay alive.
final GoRouter statefulRouter = GoRouter(
initialLocation: '/home',
routes: [
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) =>
StatefulAppShell(navigationShell: navigationShell),
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeTab(),
routes: [
GoRoute(
path: 'item/:id',
builder: (context, state) =>
ItemScreen(id: state.pathParameters['id']!),
),
],
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/search',
builder: (context, state) =>
const Center(child: Text('Search')),
),
],
),
],
),
],
);
class StatefulAppShell extends StatelessWidget {
const StatefulAppShell({super.key, required this.navigationShell});
final StatefulNavigationShell navigationShell;
@override
Widget build(BuildContext context) {
return Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
onDestinationSelected: (i) => navigationShell.goBranch(
i,
initialLocation: i == navigationShell.currentIndex,
),
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.search), label: 'Search'),
],
),
);
}
}Here the shell receives a StatefulNavigationShell instead of a plain child. It is itself the widget to place in the body. The index comes from currentIndex, so you no longer compute it from the URL. Tab changes use goBranch.
The initialLocation argument handles a common gesture. When the user taps the tab they are already on, initialLocation: true resets that branch to its first page. Without it, goBranch returns to wherever the branch last was.
Choosing between the two
| Need | ShellRoute | StatefulShellRoute.indexedStack |
|---|---|---|
| Shared bar or drawer around pages | Yes | Yes |
| Tabs keep their own back stack | No | Yes |
| Tab widgets stay alive off screen | No | Yes |
| Memory use | Lower | Higher, since every visited branch stays built |
| Selected tab | Derived from `state.uri` | `navigationShell.currentIndex` |
Choose ShellRoute for a frame around pages that behave like one flow, such as a persistent header or a drawer. Choose StatefulShellRoute for the typical bottom-tab app.
Common errors
- The bar appears on a screen that should be full-screen. The route has no
parentNavigatorKey, so it was placed in the shell's navigator. Set it to the root key. parentNavigatorKeyhas no effect or throws an assertion. The key you pass must belong to an ancestor navigator of the route. Use the sameGlobalKeyobject you gave toGoRouter(navigatorKey: ...), and create it once at file level rather than insidebuild.- The wrong tab is highlighted on deep links. Matching on equality fails for nested paths. Use
startsWithor a path-prefix check, as in the example. - Back from a tab exits the app instead of returning to Home.
context.goreplaces the stack, so there is nothing to pop. Decide whether that suits your app. If not, handle the root withPopScope, as covered in the back button chapter. - Each tab shows two app bars. The shell and the child both built a
Scaffoldwith anAppBar. Put the app bar in only one place.
Exercise
In the plain ShellRoute example, a user opens Home, taps "Open item 7", switches to Search, and taps Home again. What do they see, and what change makes the app return to Item 7 instead?
Show answer
They see the Home tab's first page, because context.go('/home') replaces the location and the inner navigator disposed the item page. Replacing ShellRoute with StatefulShellRoute.indexedStack, with one StatefulShellBranch per tab and tab changes made through navigationShell.goBranch, keeps each branch's stack alive, so Home still shows Item 7.