Sub topic 13
Customizing branch display with navigatorContainerBuilder
This chapter assumes you can already build a tabbed app with StatefulShellRoute.indexedStack, StatefulShellBranch and StatefulNavigationShell.goBranch. It also assumes you know that each branch owns its own Navigator. Here you will change how those branch navigators are arranged and shown on screen.
What the default container does
A StatefulShellRoute creates one Navigator per branch. Something has to decide how those navigators appear. StatefulShellRoute.indexedStack answers that with an IndexedStack: all visited branch navigators stay in the widget tree, and only the one at the current index is visible.
The default constructor, StatefulShellRoute(...), lets you replace that decision through the navigatorContainerBuilder parameter. Its signature is:
Widget Function(
BuildContext context,
StatefulNavigationShell navigationShell,
List<Widget> children,
)navigationShelltells you which branch is active (currentIndex).childrencontains one widget per branch, in the same order as thebrancheslist. Each widget is that branch's navigator.- The widget you return becomes the content that
StatefulNavigationShellrenders.
In practice, indexedStack is the default constructor plus a container that returns an IndexedStack. You write a different container when you want transitions between tabs, a layout that shows several branches at once, or control over what happens to hidden branches.
Where the container sits in the tree
Your builder returns the shell widget, such as a Scaffold. You pass navigationShell into it and place it in the body. That widget builds your container internally. If you never put navigationShell in the tree, no branch navigator is shown.
Two details matter here:
- A branch that the user has not visited yet has no navigator. In that slot,
childrenholds an empty placeholder widget, so the list length always equals the number of branches. childrencan be reordered, wrapped or filtered, but you should still render the widgets that the current branch needs. If you drop the current branch's navigator, the user sees nothing.
A complete example: fading between tabs
The following app replaces the instant switch with a cross-fade. Each tab shows a counter so you can check that widget state survives tab changes.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const App());
final GoRouter router = GoRouter(
initialLocation: '/home',
routes: [
StatefulShellRoute(
builder: (context, state, navigationShell) {
return ScaffoldWithNavBar(navigationShell: navigationShell);
},
navigatorContainerBuilder: (context, navigationShell, children) {
return FadingBranchContainer(
currentIndex: navigationShell.currentIndex,
children: children,
);
},
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/home',
builder: (context, state) => const CounterScreen(title: 'Home'),
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/settings',
builder: (context, state) =>
const CounterScreen(title: 'Settings'),
),
],
),
],
),
],
);
class App extends StatelessWidget {
const App({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 FadingBranchContainer extends StatelessWidget {
const FadingBranchContainer({
super.key,
required this.currentIndex,
required this.children,
});
final int currentIndex;
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Stack(
children: [
for (var i = 0; i < children.length; i++)
AnimatedOpacity(
opacity: i == currentIndex ? 1 : 0,
duration: const Duration(milliseconds: 250),
child: IgnorePointer(
ignoring: i != currentIndex,
child: TickerMode(
enabled: i == currentIndex,
child: children[i],
),
),
),
],
);
}
}
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key, required this.title});
final String title;
@override
State<CounterScreen> createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(child: Text('Count: $_count')),
floatingActionButton: FloatingActionButton(
heroTag: widget.title,
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}Increment the Home counter, switch to Settings, then switch back. The count is still there because every branch navigator stays in the tree.
Why each wrapper is there
The container has three jobs besides showing the right child.
AnimatedOpacityproduces the fade. A fully transparent widget is still laid out, painted as nothing, and still hit-testable.IgnorePointerstops taps from reaching an invisible branch. Without it, a tap on the Home screen could land on a button in the transparent Settings screen stacked above it.TickerModepauses animations and tickers in hidden branches. Without it, an invisible branch keeps running animations, such as a spinner, and uses CPU and battery.OffstageandIndexedStackalready do this for you. When you build your own container, you must add it.
You may also want to wrap hidden branches in ExcludeSemantics, so a screen reader does not read content that the user cannot see.
Stack, Offstage and state
The container decides whether hidden branches stay alive. Three common strategies behave differently:
| Strategy | Hidden branch stays built | Widget state survives | Cost |
|---|---|---|---|
| `IndexedStack` or `Offstage` for every child | Yes | Yes | Every visited branch remains in memory and can be rebuilt on changes |
| Opacity or scale animation in a `Stack` | Yes | Yes | Same as above, plus you handle input, tickers and semantics yourself |
| Return only `children[currentIndex]` | No | No | Lower memory use, but screens rebuild from scratch on every tab switch |
The third strategy is allowed. go_router still remembers each branch's location, so the user returns to the right page, but the widgets on those pages start fresh. Scroll positions and text field contents are lost. Choose it only when the memory cost of keeping branches alive matters more than preserving state.
Showing more than one branch at once
Because you receive all the branch navigators, you can show several at once. A common case is a wide-screen layout with two panes. In the container, check MediaQuery or a LayoutBuilder, then return a Row with children[0] and children[1] in Expanded widgets.
Keep two rules in mind:
- Each child widget has to appear in the tree once. Do not place the same navigator widget in two parents.
- The
currentIndexstill tells go_router which branch is active. Back button handling andgoBranchcontinue to follow it, even if you display two panes.
Common mistakes
- Forgetting
builderorpageBuilder. The default constructor needs one of them. The container builder alone is not enough. - Not placing
navigationShellin the shell widget. The container is built byStatefulNavigationShell. If it is not in the tree, nothing is rendered. - Assuming the index matches the visible child.
children[i]corresponds tobranches[i]. If you filter or reorder the list, keep your own mapping tocurrentIndex. - Treating placeholders as real screens. An unvisited branch gives you an empty widget. Do not try to animate or measure it as if it were a page.
- Leaving hidden branches interactive. Opacity, scale or offset tricks do not stop touches. Add
IgnorePointer. - Putting
navigationShellinsidenavigatorContainerBuilderagain. The container receivesnavigationShellso you can read it. Do not use it as a child widget there, or the builder will recurse into itself.
Exercise
You wrote a custom container that stacks all branch navigators and fades the inactive ones to opacity 0. Users report that tapping a button on the visible Home tab sometimes triggers an action on the hidden Settings tab, and that a progress spinner in Settings keeps running while it is hidden. Which two widgets should you wrap each child in, and what does each fix?
Show answer
Wrap each child in IgnorePointer (ignoring: i != currentIndex) so the transparent branch cannot receive taps, and in TickerMode (enabled: i == currentIndex) so animations and tickers in hidden branches stop. Offstage and IndexedStack do both of these automatically, which is why a custom opacity-based container has to add them.
Exercise
Your container returns only children[navigationShell.currentIndex]. A user scrolls halfway down a list on the Home tab, switches to Settings and comes back. What do they see, and why?
Show answer
They return to the same page in the Home branch, because go_router remembers each branch's location. The list is back at the top, because the Home navigator was removed from the widget tree while hidden and its widget state, including the scroll position, was discarded. Keeping all branch navigators in the tree, as IndexedStack or Offstage does, preserves that state.