Sub topic 9
Adding a Drawer
This chapter assumes you can build a Scaffold with an AppBar and a body, and that you have set up named routes with Navigator.pushNamed. It covers what a drawer is and how the Scaffold and AppBar connect to it. It also covers closing it correctly during navigation, opening it from your own code, and the mistakes that usually appear along the way.
What a drawer is
A drawer is a panel that slides in from the left edge of the screen over the current content. It usually holds navigation links. In Flutter it is not a separate system. You pass a Drawer widget to the drawer slot of a Scaffold, and the Scaffold handles the rest:
- It places the panel above the body and dims the body behind it with a scrim.
- It reacts to an edge swipe from the left, which opens the drawer.
- It tells the
AppBarthat a drawer exists, so the bar can show a menu icon.
The Drawer widget is only a styled Material panel. It is 304 logical pixels wide by default and has an elevation, a background color taken from the theme, and a shape. The content is whatever child you give it. A ListView is the usual choice because the menu may be taller than the screen.
A complete working example
This app has two screens. The home screen has a drawer with a link to the settings screen.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Drawer demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
initialRoute: '/',
routes: {
'/': (context) => const HomePage(),
'/settings': (context) => const SettingsPage(),
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
drawer: Drawer(
child: ListView(
children: [
const DrawerHeader(child: Text('Menu')),
ListTile(
leading: const Icon(Icons.settings),
title: const Text('Settings'),
onTap: () {
Navigator.pop(context);
Navigator.pushNamed(context, '/settings');
},
),
],
),
),
body: const Center(child: Text('Swipe from the left edge')),
);
}
}
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: const Center(child: Text('Settings go here')),
);
}
}Run it and you will see a menu icon in the top-left corner of the home screen. Tapping the icon or swiping from the left edge opens the drawer. Tapping "Settings" closes the drawer and opens the settings screen with a back arrow.
How the AppBar decides what to show on the left
You never wrote a menu icon. The AppBar chose one. When leading is null and automaticallyImplyLeading is true (the default), the AppBar looks at its surroundings and picks the widget for the leading slot:
- If the
Scaffoldhas adrawer, the bar shows aDrawerButton, which is the menu icon. Pressing it callsScaffold.of(context).openDrawer(). - Otherwise, if the current route can be popped (it was pushed on top of another route), the bar shows a
BackButton. - Otherwise, the leading slot is empty and the title moves left.
The order matters. A screen that is pushed on top of another and also has its own drawer shows the menu icon, not the back arrow. The user can still go back with the system back gesture or button, but the bar no longer shows an arrow.
Set automaticallyImplyLeading: false when you want no automatic widget at all. Set leading when you want your own, which is shown in place of any automatic one.
Close the drawer before you navigate
The drawer example calls Navigator.pop(context) before Navigator.pushNamed. The order matters, and the reason is how the Scaffold implements the drawer. When a drawer opens, the Scaffold registers a local history entry on the current route. Calling Navigator.pop first removes that entry, which closes the drawer. It does not leave the screen.
If you skip the pop and call only pushNamed, two things go wrong:
- The drawer stays open underneath the new screen. When the user comes back, the drawer is still open.
- The open drawer's local history entry is still on the home route. The first back press after returning closes the drawer instead of doing what the user expects.
Calling pop once is correct only when the drawer is open. If you call the same onTap code from somewhere else, such as a shared widget that is also used in the body, the pop would remove the screen itself. Keep drawer-specific code inside the drawer.
Push, or replace
Each pushNamed adds a route. If a drawer has links to several top-level destinations and each one is pushed, the stack grows as the user jumps between them: Home, Inbox, Sent, Inbox, and so on. Back then walks through all of that history. For top-level destinations, replace the current route instead:
onTap: () {
Navigator.pop(context); // close the drawer
Navigator.pushReplacementNamed(context, '/settings');
},Use push for drill-down screens such as a detail page. Use pushReplacement for peers that the drawer switches between. If the destination is the screen the user is already on, only close the drawer.
Opening and closing from your own code
The automatic menu button covers most cases. Sometimes you want your own leading widget, such as a custom icon or an avatar. A custom widget has to open the drawer itself, and this is where a common error appears.
// Fails at runtime when pressed:
AppBar(
leading: IconButton(
icon: const Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
),
)Here context belongs to the build method of the widget that creates the Scaffold. That context sits above the Scaffold in the tree, so Scaffold.of(context) cannot find it. Flutter throws an error saying that Scaffold.of() was called with a context that does not contain a Scaffold. The fix is to wrap the button in a Builder, which gives its callback a new context from below the Scaffold:
import 'package:flutter/material.dart';
class CustomMenuPage extends StatelessWidget {
const CustomMenuPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Custom menu'),
leading: Builder(
builder: (context) => IconButton(
icon: const Icon(Icons.account_circle),
tooltip: 'Open menu',
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
),
drawer: const Drawer(child: Center(child: Text('Drawer content'))),
body: const Center(child: Text('Body')),
);
}
}The inner context comes from the Builder, which sits inside the Scaffold's appBar slot, so the lookup succeeds. The same problem appears for any widget you build in the same build method as the Scaffold, not only the AppBar. A second fix is to give the Scaffold a GlobalKey<ScaffoldState> and call key.currentState?.openDrawer(). That needs a StatefulWidget to own the key, so Builder is usually less work.
To close the drawer from code, call Scaffold.of(context).closeDrawer() or Navigator.pop(context). Both work. Use Navigator.pop when you are about to navigate, as shown earlier.
Showing the current destination
A plain Drawer with ListTile children does not track which item is current. For simple cases, set selected: true on the matching ListTile, which tints its icon and text with the theme's primary color. For a menu that switches screens inside one Scaffold, Material 3 provides NavigationDrawer. It tracks the selected index and draws the pill-shaped highlight for you.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: MailShell()));
class MailShell extends StatefulWidget {
const MailShell({super.key});
@override
State<MailShell> createState() => _MailShellState();
}
class _MailShellState extends State<MailShell> {
static const _titles = ['Inbox', 'Starred', 'Sent'];
int _index = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(_titles[_index])),
drawer: NavigationDrawer(
selectedIndex: _index,
onDestinationSelected: (int i) {
setState(() => _index = i);
Navigator.pop(context);
},
children: [
const Padding(
padding: EdgeInsets.fromLTRB(28, 16, 16, 10),
child: Text('Mail'),
),
for (final title in _titles)
NavigationDrawerDestination(
icon: const Icon(Icons.mail_outline),
label: Text(title),
),
],
),
body: Center(child: Text('Showing ${_titles[_index]}')),
);
}
}Only NavigationDrawerDestination children count toward the index. The padded Text header does not. Here the drawer switches content inside one screen, so there is no push or replace, only a pop to close the drawer. The body should be driven by the same index.
Other drawer settings
| Property | On | Effect |
|---|---|---|
| `endDrawer` | `Scaffold` | A second drawer that slides in from the right edge. The `AppBar` shows an `EndDrawerButton` among its actions only if you add one. It is not added automatically. |
| `drawerEnableOpenDragGesture` | `Scaffold` | Set to `false` to disable the edge swipe. The menu button still works. |
| `drawerScrimColor` | `Scaffold` | Color of the dimmed overlay over the body. |
| `drawerEdgeDragWidth` | `Scaffold` | Width of the strip at the screen edge that responds to a swipe. |
| `onDrawerChanged` | `Scaffold` | Callback with `true` when the drawer opens and `false` when it closes. Useful for pausing animations or refreshing data. |
| `width` | `Drawer` | Panel width, 304 by default. |
Edge cases and common mistakes
- One drawer per Scaffold. Each screen has its own
Scaffold, so each screen that wants a drawer must declare one. A drawer on the home screen does not appear on the settings screen. If several screens share a menu, move the drawer into its own widget (for exampleAppDrawer) and pass it to eachScaffold. Chapter 11 covers that kind of split. - A drawer replaces the back arrow. If a pushed screen shows a menu icon where users expect a back arrow, this is why. Remove the
drawerfrom detail screens, or setleading: const BackButton()explicitly. - Nested Scaffolds. If a
Scaffoldsits inside anotherScaffold's body,Scaffold.of(context)finds the nearest one. The drawer you open may not be the one you meant. UseBuildercontexts deliberately or avoid nesting. - Drawer on wide screens. On a tablet or desktop window, a modal drawer over a large body looks out of place. Check the width with
MediaQuery.sizeOf(context).widthand show a permanentNavigationRailor a fixed side panel above a width of about 600 logical pixels. Use thedraweronly on narrow layouts. - Accessibility. The default menu button already has a tooltip. If you build your own leading button, give it a
tooltip, because screen readers use it as the label. - Long menus. A
Columninside aDraweroverflows when the menu is taller than the screen, for example in landscape orientation. UseListView.
Exercise
A developer writes leading: IconButton(icon: const Icon(Icons.menu), onPressed: () => Scaffold.of(context).openDrawer()) directly inside the AppBar in a StatelessWidget's build method, and the same build method creates the Scaffold. Pressing the button throws an error. Why does this happen, and how do you fix it?
Show answer
The context in the callback is the one passed to build, which sits above the Scaffold in the widget tree. Scaffold.of searches upward from that context and finds no Scaffold. Wrap the IconButton in a Builder and use the Builder's own context, which lies below the Scaffold. A GlobalKey<ScaffoldState> with currentState?.openDrawer() also works but needs a StatefulWidget.
Exercise
A drawer has three links to top-level screens, and each onTap calls Navigator.pushNamed without calling pop first. List two problems the user will see, and give the corrected onTap body for one link to '/settings'.
Show answer
First, the drawer stays open underneath the new screen, so it is still open when the user returns. Second, every selection adds another route to the stack, so back steps through every screen visited, and the first back press after returning may only close the drawer. Corrected body: Navigator.pop(context); Navigator.pushReplacementNamed(context, '/settings');.
Exercise
A pushed detail screen has a Scaffold with a drawer. The designer wants a back arrow in the AppBar instead of the menu icon, while keeping the drawer available by swiping. What do you change?
Show answer
Set leading: const BackButton() on the AppBar. An explicit leading overrides the automatic menu button. The drawer stays on the Scaffold, and the edge swipe still opens it unless drawerEnableOpenDragGesture is false.