Sub topic 11
Shared layouts with ShellRoute
This chapter assumes you can declare a GoRouter, define GoRoute paths, and tell go from push. It shows how to wrap several routes in one persistent layout, such as an app bar, a navigation bar, or a side rail, without rebuilding that layout on every navigation.
The problem a shell solves
Suppose the Feed and Settings screens both need the same NavigationBar. With plain GoRoute entries you have two options. You can put the bar inside each screen's Scaffold, or you can extract a shared widget and wrap each screen in it. Both approaches create a new bar for every navigation. The bar is torn down and rebuilt, its animations restart, and any state it holds is lost.
A ShellRoute fixes this. It places a second Navigator inside the widget your builder returns. Child routes are shown in that inner navigator, and the shell widget around it stays mounted.
How ShellRoute works
A ShellRoute has no path of its own. It only groups routes and supplies a wrapper. Its builder receives three arguments:
context: the build context.state: aGoRouterStatefor the current location.child: a widget containing the innerNavigatorthat displays the matched child route.
A complete example
The program below uses two navigator keys. The root key belongs to the router's top-level navigator. The shell key belongs to the inner one. The /details/:id route sets parentNavigatorKey to the root key, so it covers the navigation bar.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GlobalKey<NavigatorState> _rootKey =
GlobalKey<NavigatorState>(debugLabel: 'root');
final GlobalKey<NavigatorState> _shellKey =
GlobalKey<NavigatorState>(debugLabel: 'shell');
final GoRouter router = GoRouter(
navigatorKey: _rootKey,
initialLocation: '/feed',
routes: <RouteBase>[
ShellRoute(
navigatorKey: _shellKey,
builder: (context, state, child) =>
AppShell(location: state.uri.path, child: child),
routes: <RouteBase>[
GoRoute(
path: '/feed',
builder: (context, state) => const FeedScreen(),
),
GoRoute(
path: '/settings',
builder: (context, state) =>
const Center(child: Text('Settings')),
),
],
),
GoRoute(
path: '/details/:id',
parentNavigatorKey: _rootKey,
builder: (context, state) => Scaffold(
appBar: AppBar(title: Text('Item ${state.pathParameters['id']}')),
body: const Center(child: Text('Full screen, no navigation bar')),
),
),
],
);
void main() => runApp(const MyApp());
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;
int get _index => location.startsWith('/settings') ? 1 : 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: child,
bottomNavigationBar: NavigationBar(
selectedIndex: _index,
onDestinationSelected: (i) =>
context.go(i == 0 ? '/feed' : '/settings'),
destinations: const [
NavigationDestination(icon: Icon(Icons.list), label: 'Feed'),
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
],
),
);
}
}
class FeedScreen extends StatelessWidget {
const FeedScreen({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () => context.push('/details/7'),
child: const Text('Open item 7'),
),
);
}
}Three points in this code matter.
- Child paths are absolute (
/feed, notfeed). A shell adds no path segment, so top-level children must start with/. - The shell reads the current location to decide which tab to highlight. The shell widget stays mounted, so it must be told what changed. Here it receives
state.uri.pathfrom the builder, which runs again on each navigation. - The navigation bar uses
context.go, which swaps the child page. It does not stack pages.
Choosing which navigator shows a route
When you navigate to a route declared inside the shell, the page appears in the shell's inner navigator. A route declared outside the shell appears in the root navigator, and so does any route that sets parentNavigatorKey to the root key.
| Route declared | `parentNavigatorKey` | Where it appears |
|---|---|---|
| Inside the shell | not set | Inner navigator, with the shell visible |
| Inside the shell | root key | Root navigator, above the shell |
| Outside the shell | not set | Root navigator |
Use the root key for screens that should hide the shared layout: a full-screen image viewer, a checkout flow, or a login page.
Rebuilds and state
The shell widget is not recreated when you move between children. Flutter updates it with a new child. A State object inside the shell survives, so a drawer's scroll position or a search field's text is kept.
The child pages are a different matter. A plain ShellRoute shows one child at a time. When you call context.go('/settings'), the Feed page leaves the inner navigator and its state is disposed. Returning to Feed builds it from scratch. Scroll position, text input, and sub-stacks are gone.
If you need each tab to keep its own history and state, use StatefulShellRoute, covered in the next chapter.
| Feature | ShellRoute | StatefulShellRoute |
|---|---|---|
| Shared wrapper widget | Yes | Yes |
| Inner navigators | One | One per branch |
| Sibling page state kept | No | Yes |
| Extra setup | Minimal | Branches and a navigation shell |
Common errors
- Relative child path. A top-level child written as
path: 'feed'throws an assertion saying the path must start with/. Only routes nested under anotherGoRouteuse relative paths. - Shell does not update the selected tab. The shell widget stays mounted, so computing the index once in
initStategoes stale. Derive it from the location on each build, asAppShelldoes. - Back button leaves the app unexpectedly.
context.goreplaces the inner stack. If a user moves Feed to Settings withgo, there is no previous page in the inner navigator to pop. Usepushwhen you want a back step. - Dialogs and bottom sheets cover only the shell.
showDialoguses the nearest navigator by default. Called from a child page, that is the inner navigator. PassuseRootNavigator: true(the default forshowDialog) or use the root key's context when you want an overlay above the whole app. - Nested shells. You can put a
ShellRouteinside another one. Each needs its ownnavigatorKey, and a child that setsparentNavigatorKeygoes to exactly the navigator that owns that key.
Observers and page builders
ShellRoute accepts an observers list that listens only to the inner navigator. Use it to log tab-level navigation separately from root events. It also accepts pageBuilder, which lets you wrap the shell in a custom page, for example NoTransitionPage, so the shell itself does not animate when it first appears.
ShellRoute(
pageBuilder: (context, state, child) => NoTransitionPage<void>(
key: state.pageKey,
child: AppShell(location: state.uri.path, child: child),
),
routes: <RouteBase>[
GoRoute(
path: '/feed',
builder: (context, state) => const FeedScreen(),
),
],
)Summary of the decision
Use a ShellRoute when several screens share chrome and you do not mind that switching destroys the previous screen's state. Add a root navigator key when some screens must cover the chrome. Move to StatefulShellRoute when each destination needs its own preserved stack.
Exercise
In the example, the Feed screen calls context.push('/details/7') and the details route sets parentNavigatorKey: _rootKey. What changes on screen if you remove parentNavigatorKey from the details route and also move that route inside the ShellRoute's routes list? Where does the page appear, and what happens to the path you would write for it?
Show answer
The details page now appears in the shell's inner navigator, so the navigation bar stays visible below it instead of being covered. Because it would be a top-level child of the shell, its path must still start with /, so /details/:id remains valid. Pressing back pops it from the inner navigator and returns to Feed.