Sub topic 2
Defining Tabs as StatefulShellBranch Objects
This chapter assumes you know Dart basics, Flutter widgets such as Scaffold and NavigationBar, and how to define routes with GoRouter, GoRoute, and context.go. You should also understand that a Flutter Navigator keeps a stack of pages.
Defining tabs with StatefulShellBranch
A StatefulShellRoute.indexedStack holds a list of branches. Each StatefulShellBranch represents one tab. A branch owns its own subtree of routes and its own navigator, so its back stack survives while the user is on another tab.
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(),
),
],
),
],
),
],
);Building the shell UI with StatefulNavigationShell
The builder receives a StatefulNavigationShell. Place it in the body of a Scaffold. Its currentIndex tells the navigation bar which tab is active.
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,
);
},
),
);
}
}Switching tabs with goBranch
goBranch(index) switches to the branch at that index. Passing initialLocation: true sends the branch back to its first route. The code above uses this when the user taps the tab that is already active, which pops that tab to its root.
How each tab keeps its own stack and state
Each branch has its own Navigator. If the user pushes a detail page inside the Home tab, switches to Settings, and returns to Home, the detail page is still on the stack. The indexedStack variant keeps every branch in memory and shows only the active one, so widget state inside inactive tabs is preserved.
Exercise
What does navigationShell.goBranch(1, initialLocation: true) do?
Show answer
It switches to the branch at index 1 and resets that branch to its initial location, so its navigation stack returns to the root route.