Sub topic 4
Why ShellRoute is not enough for tabs
This chapter assumes you can define a GoRouter with nested GoRoute objects and navigate with context.go. It also assumes you know that Flutter's Navigator keeps a stack of pages. You will build a two-tab app with ShellRoute, watch it lose state, and learn why. That explains why the rest of this tutorial uses StatefulShellRoute.
What ShellRoute does
A ShellRoute wraps a group of routes in a persistent widget. The group's pages are shown in a new, separate Navigator. Your builder receives that navigator as a child widget and places it wherever it belongs, usually inside a Scaffold with a bottom bar.
This gives you two things:
- Persistent chrome. The widget returned by the builder stays on screen while the routes inside change. The navigation bar is not rebuilt as part of each page.
- A nested navigator. Routes inside the shell are pushed onto the shell's own navigator, not the root navigator. Their transitions happen inside the shell area only.
The shell does not give you separate histories for each section of the shell. The shell has exactly one navigator, so all its routes share one stack.
A tabbed app built with ShellRoute
This complete app has a Home tab and a Settings tab. The Home screen has a counter, so you can see whether its state survives.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const MyApp());
final GoRouter router = GoRouter(
initialLocation: '/home',
routes: [
ShellRoute(
builder: (context, state, child) => ScaffoldWithNavBar(child: child),
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'details',
builder: (context, state) => const DetailsScreen(),
),
],
),
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsScreen(),
),
],
),
],
);
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.child});
final Widget child;
@override
Widget build(BuildContext context) {
final location = GoRouterState.of(context).uri.path;
final selectedIndex = location.startsWith('/settings') ? 1 : 0;
return Scaffold(
body: child,
bottomNavigationBar: NavigationBar(
selectedIndex: selectedIndex,
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
onDestinationSelected: (index) {
context.go(index == 0 ? '/home' : '/settings');
},
),
);
}
}
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: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Counter: $_count'),
FilledButton(
onPressed: () => setState(() => _count++),
child: const Text('Increment'),
),
TextButton(
onPressed: () => context.go('/home/details'),
child: const Text('Open details'),
),
],
),
),
);
}
}
class DetailsScreen extends StatelessWidget {
const DetailsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details')),
body: const Center(child: Text('Details page')),
);
}
}
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 page')),
);
}
}The details route is a sub-route of /home. Navigating to /home/details puts two pages on the shell navigator: Home, then Details. The back arrow in the Details app bar appears because the shell navigator can pop.
Reproducing the problem
Run the app and follow these steps:
- Tap Increment three times. The counter reads 3.
- Tap Open details. The Details page appears with a back arrow, and the tab bar stays visible.
- Tap the Settings destination.
- Tap the Home destination.
You expect to land on Details, or at least on Home with a counter of 3. Instead you land on Home with the counter at 0. The Details page is gone and the back arrow does not return you to it.
Why the state is lost
Three facts explain the behavior.
One navigator holds every route in the shell. ShellRoute creates a single Navigator. Home, Details and Settings all live in its stack. The router has no concept of "the Home tab's stack" and "the Settings tab's stack". There is only one stack.
context.go replaces the stack. go does not push a page. It tells the router to jump to a new location. The router matches that location to a list of routes and gives the navigator a new list of pages. For /settings the list is just the Settings page. Flutter compares the new list with the old one, removes the pages that are no longer present, and adds the new ones.
Removed pages are disposed. When the Home and Details pages leave the list, their widgets leave the tree and their State objects are disposed, including _count. When you tap Home later, the router builds a new HomeScreen from scratch.
| Aspect | ShellRoute behavior |
|---|---|
| Persistent widget around the pages | Yes, the builder's widget stays mounted |
| Number of navigators inside the shell | One |
| Back stack per tab | No, one shared stack |
| Widget state of a tab you left | Disposed |
| Where `Details` appears after returning to Home | Nowhere, the stack was replaced |
Workarounds and their cost
Developers worked around this before StatefulShellRoute existed. Each workaround has a real cost.
- Remember the last location per tab. Store the most recent URL of each tab in a variable. When the user taps a tab, call
context.gowith that URL. This restores the stack depth, because/home/detailsrebuilds Home and Details. It does not restore widget state. The counter still resets, and so do scroll positions and text fields. Pages that were rebuilt also reload their data. - Keep state outside the widgets. Move the counter into a provider or another state holder that outlives the pages. This works for state you choose to lift. It does not cover scroll offsets, form text, or animation state that you would otherwise get for free.
- Use one ShellRoute per tab. You can create separate shells, each with its own navigator key, and wire them together by hand. The result is complex and fragile, and the bar has to be placed outside them.
- Put an
IndexedStackof navigators in the shell yourself. This is whatStatefulShellRoutedoes, but written by hand. It requires you to manage navigators and keys againstgo_routerinternals.
None of these gives you what a tab bar normally promises: each tab remembers where you were and what you typed.
When ShellRoute is the right tool
ShellRoute is not a worse StatefulShellRoute. It is a simpler tool with a different purpose. Choose it when the shell's children are not parallel sections that each need memory.
- A persistent wrapper for one flow. Examples are an onboarding flow with a progress header, or a checkout flow with a fixed order summary.
- Section switching where a fresh start is intended. A navigation rail that opens independent top-level pages, where returning to a page should show it new, is a good fit.
- Shared chrome without per-section history. An app-wide scaffold with a drawer or a title bar that reads from the current route is a good fit.
Choose StatefulShellRoute when you can answer yes to this question: "If the user leaves this section and comes back, should they find it exactly as they left it?" Bottom navigation bars in most mobile apps meet this test.
What a tab-friendly shell needs
Compare the reproduction above with what a tab bar needs, and the requirements are clear:
- One navigator for each tab, so each tab has its own back stack.
- All of those navigators kept alive while a tab is hidden, so widget state survives.
- A way to switch the visible tab without replacing any stack.
- A way to reset one tab to its starting page on demand.
ShellRoute provides none of these. The next chapter introduces StatefulShellRoute.indexedStack, which does. It gives each tab a StatefulShellBranch with its own navigator. A StatefulNavigationShell widget switches between branches. The switching operation, goBranch, changes which branch is visible and leaves the others untouched.
Check your understanding
Exercise
In the ShellRoute example, you tap Increment three times, tap the Settings destination, then tap Home. Why does the counter show 0, and which Flutter object is responsible for losing the value?
Show answer
The shell has a single navigator, and context.go('/settings') replaces its page list with only the Settings page. The Home page leaves the list, so its widget is removed and its State object, which holds count, is disposed. Tapping Home builds a new HomeScreen with a fresh State where count starts at 0.
Exercise
A teammate fixes the problem by saving each tab's last URL and calling context.go with it when a tab is tapped. Name one thing this restores and one thing it does not.
Show answer
It restores the page stack depth, so Home and Details are rebuilt for /home/details. It does not restore widget state such as a counter, scroll offset or typed text, because the pages are created again from scratch.
Exercise
Give one app layout where ShellRoute is a better choice than StatefulShellRoute, and say why.
Show answer
A checkout or onboarding flow with a fixed header or summary. It needs persistent chrome around one linear flow, with a single stack and no requirement that hidden sections keep their own history, so the extra navigators of StatefulShellRoute are unnecessary.