Sub topic 5
Customizing the AppBar: title, leading, and actions
This chapter assumes you can write a StatelessWidget, you know Dart named parameters, and you have a running app with a MaterialApp and a Scaffold that has an AppBar. Here you will configure the three slots of the bar: title, leading, and actions. You will also see how Flutter fills leading for you, and which mistakes show up most often.
The three slots
An AppBar is a row with three horizontal regions.
| Slot | Position | Type | Typical content |
|---|---|---|---|
| `leading` | Start edge | `Widget?` | Menu icon, back button, close button |
| `title` | Middle | `Widget?` | A `Text`, or a small layout such as a `Column` |
| `actions` | End edge | `List<Widget>?` | Icon buttons, a popup menu |
All three take widgets, not strings. title: 'Inbox' does not compile. You write title: const Text('Inbox'). Because the title is a widget, you can put a logo, a search field, or a two-line layout there.
The bar's height defaults to 56 logical pixels (kToolbarHeight). You can change it with toolbarHeight.
A complete example
This app uses all three slots. It has a drawer so you can see the automatic menu icon, and a popup menu in actions.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
enum InboxMenu { markAllRead, settings }
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Inbox demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
home: const InboxPage(),
);
}
}
class InboxPage extends StatelessWidget {
const InboxPage({super.key});
void _onMenuSelected(BuildContext context, InboxMenu choice) {
final text = switch (choice) {
InboxMenu.markAllRead => 'All messages marked as read',
InboxMenu.settings => 'Settings tapped',
};
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(text)),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Inbox'),
Text('3 unread', style: TextStyle(fontSize: 12)),
],
),
actions: [
IconButton(
icon: const Icon(Icons.search),
tooltip: 'Search',
onPressed: () {},
),
PopupMenuButton<InboxMenu>(
tooltip: 'More options',
onSelected: (choice) => _onMenuSelected(context, choice),
itemBuilder: (context) => const [
PopupMenuItem(
value: InboxMenu.markAllRead,
child: Text('Mark all read'),
),
PopupMenuItem(
value: InboxMenu.settings,
child: Text('Settings'),
),
],
),
],
),
drawer: const Drawer(child: Center(child: Text('Menu'))),
body: const Center(child: Text('No messages')),
);
}
}Run it and note three things you did not write: a menu icon at the start, a title aligned to the start edge on Android, and a tooltip on each button. The next sections explain each.
The title
title accepts any widget, but the bar gives it limited space. Flutter lays out the title between leading and actions. If it is too long, a Text is cut off at the edge, or you get an overflow error when the title is a Row.
Two properties control how the title looks:
centerTitleis abool?. When it isnull, the platform decides: centered on iOS and macOS, start-aligned elsewhere. Settrueorfalseto get the same result on every platform.titleSpacingis the gap betweenleadingand the title. With Material 3 the default is generally fine. Set it to0when you want the title flush against the leading widget.
For a long title, constrain it explicitly:
AppBar(
title: const Text(
'A very long conversation subject that will not fit',
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
)The text style comes from the theme (AppBarTheme.titleTextStyle, falling back to TextTheme.titleLarge in Material 3). Do not style each title by hand if you want the same style across the app. Set it once in ThemeData(appBarTheme: AppBarTheme(...)). The theming chapter covers that.
The leading widget
leading sits at the start edge: the left in left-to-right languages, the right in right-to-left ones. Flutter handles that flip for you, so do not hard-code left or right.
You usually do not set leading yourself, because the AppBar chooses a widget when you leave it null. The order of choice is below.
Two consequences follow from this order:
- A drawer wins over a back button. If a pushed screen has both a drawer and a previous route, the user sees the menu icon and loses the automatic back button. Either remove the drawer from that screen, or set
leading: const BackButton()yourself. - Setting
leadingreplaces whatever Flutter would have chosen. If you set a custom icon on a pushed screen, you now own the "go back" behavior.
Setting your own leading widget
This version of a screen puts a close button on a pushed page, which suits editing screens where "close" reads better than "back":
class ComposePage extends StatelessWidget {
const ComposePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: const CloseButton(),
title: const Text('New message'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Send'),
),
],
),
body: const Center(child: Text('Write something')),
);
}
}CloseButton and BackButton call Navigator.maybePop by default, so you do not need an onPressed. If you build the button yourself with IconButton, you must wire it:
leading: IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: 'Back',
onPressed: () => Navigator.maybePop(context),
),An IconButton with onPressed: null is drawn disabled and ignores taps. That is the most common reason a hand-built back button "does nothing".
Opening a drawer from a custom leading
If you replace the menu icon, you must open the drawer yourself with Scaffold.of(context).openDrawer(). The context has to sit below the Scaffold. In the example above, the context passed to HomePage.build is above the Scaffold that build returns, so Scaffold.of(context) would fail or find the wrong scaffold. Wrap the button in a Builder to get a context that is inside the scaffold:
leading: Builder(
builder: (context) => IconButton(
icon: const Icon(Icons.menu),
tooltip: 'Open menu',
onPressed: () => Scaffold.of(context).openDrawer(),
),
),Hiding or resizing the slot
automaticallyImplyLeading: falsestops Flutter from inserting a menu or back button. Use it on a root screen where a back button makes no sense, or when the drawer is opened some other way.leadingWidthchanges how much room the slot gets. The default is 56. Raise it if you put a wider widget there, such as an avatar with a label, or it will be clipped.
Actions
actions is a list of widgets placed at the end edge, in the order you list them. The last item is closest to the edge.
Guidelines that hold up in practice:
- Use
IconButtonfor each action, and always supplytooltip. It gives mouse users a hover label and gives screen readers a name for the button. An icon-only button without a tooltip is announced as just "button". - Keep to two or three visible actions on a phone. Move the rest into a
PopupMenuButton, as in the first example. - A
TextButtonis acceptable for one clear commit action such as "Send" or "Save".
Each IconButton has a minimum tap target of 48 by 48 pixels, so the bar fits about five before the title is squeezed. There is no scrolling or wrapping. When actions plus leading take too much space, the title shrinks, and then an overflow error appears if the title is a Row.
The popup menu
PopupMenuButton<T> needs itemBuilder, which returns a list of PopupMenuEntry<T>, and usually onSelected, which receives the value of the chosen item. Giving it an enum for T keeps the menu type-safe, as in the first example. If you use onSelected, do not also put onTap on the items for the same purpose, or the action can run twice.
Appearance properties
These properties change how the bar looks without touching its structure:
| Property | Effect |
|---|---|
| `backgroundColor` | Fill color. Defaults to the theme's surface color in Material 3. |
| `foregroundColor` | Color of the title text and icons. |
| `elevation` | Shadow at rest. Material 3 defaults to 0. |
| `scrolledUnderElevation` | Elevation when content scrolls beneath the bar. This is why the bar can change tint as you scroll. |
| `iconTheme` and `actionsIconTheme` | Size and color for leading icons and action icons. |
| `bottom` | A `PreferredSizeWidget` under the toolbar, usually a `TabBar`. |
Prefer a theme-wide setting over per-bar overrides. If you set backgroundColor on one bar and later change the seed color, that bar will not follow.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `title: 'Inbox'` fails to compile | The slot takes a `Widget` | Use `const Text('Inbox')` |
| The back button disappeared | The Scaffold has a `drawer`, or you set `leading` | Set `leading: const BackButton()` or remove the drawer on that screen |
| Menu icon appears on a screen where you did not want one | `drawer` is set and `automaticallyImplyLeading` is true | Set `automaticallyImplyLeading: false` |
| `Scaffold.of() called with a context that does not contain a Scaffold` | The context is above the Scaffold | Wrap the widget in a `Builder`, or move the Scaffold into a child widget |
| An action button does nothing | `onPressed` is `null` or the empty `() {}` placeholder was never replaced | Provide a real callback |
| Title overflow stripes | A long `Row` or `Text` with no limit | Use `maxLines` and `overflow`, or shorten the title |
| Title not centered on Android | `centerTitle` defaults to `null` | Set `centerTitle: true` |
Exercises
Exercise
A pushed SettingsPage has a Scaffold with drawer: Drawer() and an AppBar with no leading. The user arrived by Navigator.pushNamed. Which icon does the AppBar show at the start, and how do you make it show a back button?
Show answer
It shows the menu icon, because a drawer takes priority over the implied back button. To get a back button, set leading: const BackButton() on the AppBar, or remove the drawer from that screen.
Exercise
Why does onPressed: () => Scaffold.of(context).openDrawer() fail when context is the parameter of the build method that also creates the Scaffold, and what is the fix?
Show answer
That context belongs to a widget above the Scaffold, so Scaffold.of cannot find it. Wrap the button in a Builder so its context is inside the Scaffold, or move the Scaffold into a separate child widget.
Exercise
Write an AppBar for a chat screen. It has a title Text('Alex') that is always centered, no automatic leading widget, and one action: an IconButton with a call icon and the tooltip Call.
Show answer
AppBar( centerTitle: true, automaticallyImplyLeading: false, title: const Text('Alex'), actions: [ IconButton( icon: const Icon(Icons.call), tooltip: 'Call', onPressed: () {}, ), ], )