Sub topic 9
Switching between bottom bar and navigation rail
This chapter assumes you know Scaffold, Row and Expanded, and StatefulWidget with setState. It also assumes you have read the earlier chapters on MediaQuery, LayoutBuilder and window-size breakpoints. Here you will use those tools to build an app shell, the outer widget that holds the navigation and the current page.
Why navigation changes with window size
A bottom bar suits a phone held in one hand. The thumb reaches the bottom edge, and the bar uses a short strip of height that is cheap on a tall screen. On a wide window the same bar stretches across 1200 pixels, which makes the targets far apart and leaves the page with little vertical room.
Material 3 recommends a different pattern for wider windows. A navigation rail is a vertical strip of destinations along the leading edge of the screen. It keeps targets close together and gives the page full height.
| Window-size class | Width in logical pixels | Recommended navigation |
|---|---|---|
| Compact | under 600 | `NavigationBar` at the bottom |
| Medium | 600 to under 840 | `NavigationRail` |
| Expanded | 840 and above | `NavigationRail`, optionally extended with labels beside the icons |
The shell in this chapter makes a two-way choice at 600 pixels. A later section adds the third tier.
The shell structure
The shell has three parts.
- A single
selectedIndexthat records the current destination. - A decision about which navigation widget to show.
- A page area that reads the same index whichever widget is visible.
The index belongs in the shell's State object, not in the navigation widgets. NavigationBar and NavigationRail are both stateless. They display the selectedIndex you give them and call onDestinationSelected when the user taps. Because the shell owns the index, a window resize that swaps one widget for the other loses nothing.
The complete shell
This is the full shell. It uses MediaQuery.sizeOf for the decision.
import 'package:flutter/material.dart';
class AdaptiveShell extends StatefulWidget {
const AdaptiveShell({super.key});
@override
State<AdaptiveShell> createState() => _AdaptiveShellState();
}
class _AdaptiveShellState extends State<AdaptiveShell> {
int _index = 0;
static const _pages = [Text('Home'), Text('Search'), Text('Settings')];
@override
Widget build(BuildContext context) {
final useRail = MediaQuery.sizeOf(context).width >= 600;
final body = Center(child: _pages[_index]);
return Scaffold(
body: useRail
? Row(
children: [
NavigationRail(
selectedIndex: _index,
onDestinationSelected: (i) => setState(() => _index = i),
labelType: NavigationRailLabelType.all,
destinations: const [
NavigationRailDestination(
icon: Icon(Icons.home), label: Text('Home')),
NavigationRailDestination(
icon: Icon(Icons.search), label: Text('Search')),
NavigationRailDestination(
icon: Icon(Icons.settings), label: Text('Settings')),
],
),
const VerticalDivider(width: 1),
Expanded(child: body),
],
)
: body,
bottomNavigationBar: useRail
? null
: NavigationBar(
selectedIndex: _index,
onDestinationSelected: (i) => setState(() => _index = i),
destinations: const [
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
NavigationDestination(icon: Icon(Icons.search), label: 'Search'),
NavigationDestination(
icon: Icon(Icons.settings), label: 'Settings'),
],
),
);
}
}To run it, pass the shell to MaterialApp(home: AdaptiveShell()). On a desktop target, drag the window edge across 600 pixels and watch the navigation move.
How the pieces fit
The rail lives inside the body. Scaffold has a bottomNavigationBar slot but no slot for a side rail. The rail goes in a Row in the body, next to an Expanded page area. Expanded hands the remaining width to the page. Without it, the Row would give the page unbounded width and Flutter would report a layout error.
The rail gets its height from the Scaffold. The Scaffold body has tight constraints, so the Row fills the available height. NavigationRail needs a bounded height. If you place a rail in a Row inside a Column or a scrolling widget, you will get a "unbounded height" error. Wrap it in Expanded or a SizedBox with a fixed height.
Both bars use destinations of different types. The bar takes NavigationDestination, which has a String label. The rail takes NavigationRailDestination, whose label is a Widget. The two types do not share a base class, so you cannot reuse one list. Section "Removing the duplication" shows how to build both from one description.
The divider is cosmetic. VerticalDivider(width: 1) draws a thin line between the rail and the page. It also takes exactly one pixel of width, which is why you set width: 1 and do not let it default to 16.
Choosing the width source
The shell reads MediaQuery.sizeOf(context).width. That is the width of the whole window. For a shell that fills the window, this is the right number, because the navigation belongs to the window.
Use LayoutBuilder instead if the shell may be embedded in a smaller area. Examples are a preview pane, a dialog, or one side of a split view. LayoutBuilder reports the constraints of the shell's parent, so the decision follows the space the shell actually receives.
LayoutBuilder(
builder: (context, constraints) {
final useRail = constraints.maxWidth >= 600;
// build the same Scaffold as before
return const SizedBox.shrink();
},
)Prefer MediaQuery.sizeOf over MediaQuery.of(context).size. The sizeOf form makes the widget depend only on the size. With of, the widget also rebuilds when unrelated data changes, such as the keyboard insets or text scale.
Removing the duplication
The shell above repeats the destination list. A small description class fixes this and keeps the two widgets in step.
import 'package:flutter/material.dart';
class Destination {
const Destination(this.icon, this.label);
final IconData icon;
final String label;
}
const destinations = [
Destination(Icons.home, 'Home'),
Destination(Icons.search, 'Search'),
Destination(Icons.settings, 'Settings'),
];
List<NavigationDestination> barDestinations() => [
for (final d in destinations)
NavigationDestination(icon: Icon(d.icon), label: d.label),
];
List<NavigationRailDestination> railDestinations() => [
for (final d in destinations)
NavigationRailDestination(icon: Icon(d.icon), label: Text(d.label)),
];In the shell, replace the two inline lists with barDestinations() and railDestinations(). Adding a fourth destination now takes one line. A mismatch between bar and rail, where one shows four items and the other three, can no longer happen.
Adding an extended rail
On expanded windows you can show icons with labels beside them. Set extended: true on the rail. The rail then widens to fit the labels.
NavigationRail(
extended: MediaQuery.sizeOf(context).width >= 840,
selectedIndex: _index,
onDestinationSelected: (i) => setState(() => _index = i),
destinations: railDestinations(),
)Note that this snippet leaves out labelType. When extended is true, labelType must be null or NavigationRailLabelType.none. Setting it to all together with extended: true fails an assertion in debug mode. If you keep labelType: all for the medium tier, compute the label type from the same width test:
final extended = width >= 840;
// ...
labelType: extended ? NavigationRailLabelType.none : NavigationRailLabelType.all,Keeping page state across switches
The shell above rebuilds the page from _pages[_index]. Each time you change destinations, the old page is discarded and its scroll position and text input are lost. That is acceptable for the three Text placeholders here. For real screens, use IndexedStack so every page stays alive:
final body = IndexedStack(index: _index, children: pages);IndexedStack builds all children up front and paints only the one at index. This is the simplest way to keep scroll positions. For apps with deep navigation inside each tab, routing packages such as go_router offer shell routes that keep a separate navigator for each destination. That is outside this chapter.
Switching between bar and rail does not itself reset page state, as long as the page widgets sit in the same position of the tree. In the shell above, the body widget appears in different parents depending on useRail: inside a Row for the rail layout, or directly in the Scaffold for the bar layout. Flutter sees a different parent, so it rebuilds the page subtree when you cross the breakpoint. If a page holds important state, give it a GlobalKey or lift the state above the shell.
Common mistakes
- Using the device's orientation as the signal. A tablet in portrait can be wider than a phone in landscape. Test the width.
- Hiding the bar without moving the destinations. If you remove the
NavigationBarand forget the rail, wide windows have no way to navigate. - Mismatched indexes. Keep one
selectedIndexand give both widgets the same destination count. ANavigationBarneeds at least two destinations, and an out-of-rangeselectedIndexfails an assertion. - A rail in an unbounded parent. Place the rail in a
Rowthat has a bounded height, as described above. - Flicker at the boundary. On desktop, a user dragging the window edge across 600 pixels will see the layout switch. This is correct behavior. Do not add hysteresis unless you see real jitter.
Testing both layouts
Set the simulated window size and check which widget is present. This test covers the narrow case, to complement a wide-window test.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('uses a bottom bar on narrow windows', (tester) async {
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(const MaterialApp(home: AdaptiveShell()));
expect(find.byType(NavigationBar), findsOneWidget);
expect(find.byType(NavigationRail), findsNothing);
});
}Setting devicePixelRatio to 1.0 makes physical and logical pixels equal, so Size(400, 800) means 400 logical pixels wide. Without it, the default ratio of 3.0 in the test environment would turn 1200 physical pixels into 400 logical ones. The addTearDown(tester.view.reset) call restores the default window so later tests are not affected.
Exercise
A shell shows a NavigationRail when the window is at least 600 logical pixels wide. A test sets tester.view.physicalSize to Size(1200, 800) but forgets to set devicePixelRatio, which defaults to 3.0 in the test environment. Which navigation widget does the test find, and why?
Show answer
It finds the NavigationBar. The logical width is physical width divided by device pixel ratio, so 1200 / 3.0 = 400 logical pixels. That is under 600, so the shell builds the bottom bar. Setting devicePixelRatio to 1.0 makes the logical width 1200 and produces the rail.
Exercise
You add extended: true to a NavigationRail that also has labelType: NavigationRailLabelType.all. What happens in debug mode, and how do you fix it?
Show answer
An assertion fails, because an extended rail already shows labels and does not allow a label type other than none. Remove labelType, set it to NavigationRailLabelType.none, or choose the label type from the same width test that sets extended.