Sub topic 7
Building the shell UI with StatefulNavigationShell
The previous chapters set up StatefulShellRoute.indexedStack and its branches. This chapter covers the widget that go_router passes to your builder, StatefulNavigationShell, and how to build a tab scaffold around it. It assumes you can write a StatelessWidget, use Scaffold, and read a GoRouter configuration with GoRoute and StatefulShellBranch.
What the builder gives you
StatefulShellRoute.indexedStack takes a builder with three arguments: context, state and navigationShell. The third argument is a StatefulNavigationShell. It is a widget, and you do not create it yourself. go_router creates one and hands it to you each time the shell needs to be built.
The StatefulNavigationShell does three jobs:
- It is the content. When you place it in your widget tree, it displays the navigators of all branches. With
indexedStack, it keeps them in anIndexedStackand shows only the active one. - It reports which branch is active through
currentIndex. - It switches branches through
goBranch.
Everything around it, such as the Scaffold, the NavigationBar, an AppBar or a side rail, is your code. go_router has no opinion about the chrome. It only requires that you put the navigationShell somewhere in the tree.
The following table lists the members you will use most.
| Member | Type | Purpose |
|---|---|---|
| `currentIndex` | `int` | Index of the active branch in the `branches` list |
| `goBranch(index, {initialLocation})` | method | Activates a branch, optionally resetting it to its first route |
| `route` | `StatefulShellRoute` | The route configuration that owns this shell |
| `shellRouteContext` | `ShellRouteContext` | Lower-level information about the shell, rarely needed in app code |
How the pieces fit together
The diagram shows how a navigation request flows through the shell. The shell widget is built once and stays in the tree while the user moves between tabs.
The NavigationBar does not keep a selected index of its own. It reads currentIndex from the shell, and a tap calls goBranch. The shell updates currentIndex, and both the bar and the body rebuild to match.
A complete minimal app
The next listing is a full main.dart you can run in a new project that has go_router as a dependency. The screens are placeholders so that the focus stays on the shell.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const MyApp());
final GoRouter router = GoRouter(
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(),
),
],
),
],
),
],
);
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 StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return const Center(child: Text('Home'));
}
}
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
return const Center(child: Text('Settings'));
}
}Three details in ScaffoldWithNavBar matter.
body: navigationShellis what makes the screens appear. The shell widget is the body. You do not wrap it in aNavigatoror anIndexedStack.selectedIndex: navigationShell.currentIndexties the highlighted tab to the router state.- The destinations list must have the same length and order as the
brancheslist. Destination 0 corresponds to branch 0, and so on.
Why selectedIndex comes from currentIndex
A common first attempt keeps a _selectedIndex in a StatefulWidget and updates it with setState when the user taps. That works until something other than a tap changes the location. For example:
- A deep link opens
/settingswhile the app is on Home. - On web, the user edits the URL or uses the browser back button.
- Code elsewhere calls
context.go('/settings').
In each case the router changes the active branch without going through your onDestinationSelected. If you stored the index yourself, the bar would highlight the wrong tab. currentIndex is derived from the current location, so it is always correct.
What the tap handler does
The handler in the listing calls goBranch with two arguments. The first is the target index. The second, initialLocation, is true only when the tapped destination is already active. In that case the branch is sent back to its first route, so tapping the active Home tab while deep in a details page returns to the Home root. When the user taps a different tab, initialLocation is false, and the branch resumes wherever it was. The next chapter covers goBranch in more detail, so here it is enough to know that the shell widget is where you call it.
Adapting the shell to wide screens
Because the shell widget is ordinary Flutter code, you can change its layout by screen size. The same navigationShell goes in either layout. The following version shows a NavigationRail on wide screens and a NavigationBar on narrow ones. It replaces ScaffoldWithNavBar from the previous listing.
class ScaffoldWithNavBar extends StatelessWidget {
const ScaffoldWithNavBar({super.key, required this.navigationShell});
final StatefulNavigationShell navigationShell;
void _onSelected(int index) {
navigationShell.goBranch(
index,
initialLocation: index == navigationShell.currentIndex,
);
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= 600) {
return Scaffold(
body: Row(
children: [
NavigationRail(
selectedIndex: navigationShell.currentIndex,
onDestinationSelected: _onSelected,
labelType: NavigationRailLabelType.all,
destinations: const [
NavigationRailDestination(
icon: Icon(Icons.home),
label: Text('Home'),
),
NavigationRailDestination(
icon: Icon(Icons.settings),
label: Text('Settings'),
),
],
),
const VerticalDivider(width: 1),
Expanded(child: navigationShell),
],
),
);
}
return Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
onDestinationSelected: _onSelected,
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(
icon: Icon(Icons.settings),
label: 'Settings',
),
],
),
);
},
);
}
}When the window is resized across the 600 pixel breakpoint, the navigationShell moves to a different position in the tree. Because the Scaffold is rebuilt in a different structure, Flutter may recreate the subtree beneath it. Branch navigators can then be rebuilt and lose widget state such as scroll position. If your app must survive resizing with all tab state intact, keep one Scaffold and change only its bottomNavigationBar and the rail, or give the shell a GlobalKey. Test this on a desktop or web build before shipping.
Where the shell's BuildContext sits
The context in your shell widget is above the branch navigators. That has two consequences.
context.go('/settings')works there, and so does any other call that goes through go_router. The router is found through an inherited widget, not through a navigator.Navigator.of(context)from the shell widget finds the root navigator, not a branch navigator. CallingNavigator.of(context).push(...)from the bar pushes onto the root, covering the whole shell.
Screens inside a branch have a different context, one that sits below that branch's navigator. A Navigator.of(context).push from there targets the branch navigator. Prefer context.push and context.go throughout so you do not have to track which navigator you are on.
Common mistakes in the shell widget
- Forgetting to put
navigationShellin the tree. The bar appears but the body is empty. The shell is the only thing that displays branch content. - Mismatched destination and branch counts. More branches than destinations makes some tabs unreachable from the UI. More destinations than branches makes
goBranchreceive an index that has no branch, which fails with a range error. - Adding an
AppBarin the shell for every tab. The title then cannot differ per screen. Put theAppBarin each screen's ownScaffoldand keep the shell responsible only for navigation chrome. NestedScaffoldwidgets are fine. - Wrapping
navigationShellin something that rebuilds it with a new key. A changing key discards the subtree and its state. - Constructing a
StatefulNavigationShellyourself. Use only the instance passed to the builder.
Exercise
A teammate adds an int _index field to a stateful shell widget and sets it in onDestinationSelected before calling goBranch. A push notification opens the deep link /settings while the app shows Home. What goes wrong, and what is the fix?
Show answer
The router switches to the Settings branch without calling onDestinationSelected, so _index still holds the Home index and the NavigationBar highlights Home while Settings is displayed. The fix is to remove _index and pass navigationShell.currentIndex as selectedIndex, so the highlighted tab always follows the router.
Exercise
In the shell widget, onDestinationSelected calls navigationShell.goBranch(index) with no initialLocation argument. The user is on a details page inside Home and taps the Home destination. What happens, and how do you make the tap return to the Home root?
Show answer
The tap does nothing visible, because Home is already the active branch and goBranch keeps the branch's current stack. Pass initialLocation: index == navigationShell.currentIndex so that tapping the active destination resets the branch to its first route.