Sub topic 4
AppBar: the top bar of a screen
This chapter assumes you can read basic Dart (classes, constructors, named parameters) and can run a Flutter app. It also assumes you know how StatelessWidget and build work, and that you have seen MaterialApp and Scaffold in the earlier chapters. Here the focus is AppBar. You will see what it is responsible for, where it gets its defaults, and which mistakes come up most often.
What AppBar does
AppBar is the Material widget for the top bar of a screen. It usually holds a title, a navigation button on the left, and a few action buttons on the right. It does not own any state or navigation logic. It reads its context and decides what to show.
An AppBar takes its information from three sources:
- The
Scaffoldabove it. It asks whether the scaffold has a drawer. - The
Navigatorroute it sits in. It asks whether the route can be popped. - The
Theme. It reads colors, text styles, and sizes fromThemeDataandColorScheme.
Because of this, a plain AppBar(title: Text('Home')) often shows more than you wrote. It may add a menu button or a back button on its own.
Where it sits in the tree
Scaffold has an appBar slot, and that slot is the normal place for an AppBar. The scaffold gives the bar the full width at the top. It lays the body out below the bar.
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: 'AppBar demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
home: const HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: const Center(child: Text('Hello, AppBar')),
);
}
}The nesting is MaterialApp → Scaffold → AppBar. MaterialApp provides the theme and the Navigator. Scaffold provides the slot and the drawer information. AppBar consumes all of it.
The PreferredSizeWidget contract
The appBar parameter of Scaffold does not take any Widget. Its type is PreferredSizeWidget. This is an interface with one extra member:
Size get preferredSize;The scaffold reads preferredSize.height to decide how much room to reserve at the top, before it lays out the body. Most widgets don't know their height in advance, so they can't implement this. AppBar can, because its height is the toolbar height (56 logical pixels by default, available as kToolbarHeight) plus the height of a bottom widget, if you give it one.
The status bar area is a separate matter. The AppBar adds the top safe-area padding itself, so the bar draws behind the status bar and its content starts below it. You don't wrap an AppBar in SafeArea.
If you need to put something that isn't an AppBar in that slot, wrap it in PreferredSize:
Scaffold(
appBar: const PreferredSize(
preferredSize: Size.fromHeight(72),
child: ColoredBox(
color: Colors.indigo,
child: SafeArea(child: Center(child: Text('Custom bar'))),
),
),
body: const SizedBox.expand(),
)Here you are responsible for the status bar yourself, which is why the example uses SafeArea.
Properties that shape the bar
You will use these properties most often. Title, leading, and actions get their own chapter, so this table covers the rest.
| Property | Type | What it controls |
|---|---|---|
| `title` | `Widget?` | The main content. Usually a `Text`. |
| `leading` | `Widget?` | The widget at the start edge. Replaces the implied one. |
| `automaticallyImplyLeading` | `bool` | Whether a drawer or back button may be added. Default `true`. |
| `actions` | `List<Widget>?` | Widgets at the end edge. |
| `backgroundColor` | `Color?` | Bar color. Overrides the theme. |
| `foregroundColor` | `Color?` | Color of the title text and icons. |
| `elevation` | `double?` | Shadow depth when nothing scrolls under the bar. |
| `scrolledUnderElevation` | `double?` | Elevation once content scrolls under the bar (Material 3). |
| `centerTitle` | `bool?` | Whether the title is centered. |
| `toolbarHeight` | `double?` | Height of the toolbar row. Default 56. |
| `bottom` | `PreferredSizeWidget?` | A second row under the toolbar, often a `TabBar`. |
| `flexibleSpace` | `Widget?` | A widget stretched behind the whole bar, such as a gradient. |
| `systemOverlayStyle` | `SystemUiOverlayStyle?` | Status bar icon brightness. |
Where the defaults come from
If you set nothing, the bar gets its look from the theme. With useMaterial3: true, which is the default in current Flutter versions, the defaults are:
- The background is
colorScheme.surface. - The foreground is
colorScheme.onSurface. - The elevation is 0.
scrolledUnderElevationis 3.
In Material 2 the background was colorScheme.primary. Old tutorials show a bright colored bar for that reason. If your bar looks pale compared with a screenshot in an older tutorial, the theme version is the cause.
With Material 3 the bar is flat while the body is at rest. When a scrollable body moves content underneath it, the bar picks up a tint, using the scrolled-under elevation and the surface tint color. It changes back when the content returns to the top. This happens only when the body scrolls and the scroll notification reaches the bar. A body that doesn't scroll never triggers it.
To change the bar for the whole app, use appBarTheme instead of repeating arguments on each screen:
MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
appBarTheme: AppBarTheme(
centerTitle: true,
backgroundColor: Colors.teal.shade700,
foregroundColor: Colors.white,
),
),
home: const HomePage(),
)An argument on the AppBar itself wins over appBarTheme. The theme wins over the built-in defaults.
The automatic leading widget
The flowchart above shows the order the bar follows. Three consequences matter in practice.
A pushed screen gets a back button for free. When you call Navigator.pushNamed(context, '/settings'), the new route can be popped, so its AppBar shows a BackButton. Pressing it calls Navigator.maybePop. You write no code for this.
A drawer wins over the back button. If a screen has both a drawer and a route below it, the bar shows the menu icon, not the back arrow. The user can still go back with the system gesture or the system back button, but the bar no longer offers it. If you need both, build your own leading.
Your own leading replaces both. Setting leading turns the automatic behavior off for that slot. Setting automaticallyImplyLeading: false removes the automatic widget without adding one. This is the usual fix for a login screen that was pushed with pushReplacement but still shows a stray arrow, or for a root screen that should not offer a way back.
Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Welcome'),
),
body: const Center(child: Text('No back button here')),
)A second row: the bottom slot
bottom takes a PreferredSizeWidget. The usual choice is a TabBar, which already implements that interface. The bar's total height becomes the toolbar height plus the height of bottom, and the scaffold adjusts the body to match.
A TabBar needs a TabController. DefaultTabController provides one to everything below it, so it must wrap the Scaffold, not sit inside the body.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: TabsPage()));
class TabsPage extends StatelessWidget {
const TabsPage({super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: const Text('Library'),
bottom: const TabBar(
tabs: [
Tab(text: 'Books'),
Tab(text: 'Audio'),
],
),
),
body: const TabBarView(
children: [
Center(child: Text('Books')),
Center(child: Text('Audio')),
],
),
),
);
}
}Reusing a bar: your own PreferredSizeWidget
When several screens share the same bar, you can wrap AppBar in a class of your own. The class must implement PreferredSizeWidget so the scaffold accepts it, and it must report the height of the bar it builds.
import 'package:flutter/material.dart';
class BrandBar extends StatelessWidget implements PreferredSizeWidget {
const BrandBar({super.key, required this.title});
final String title;
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return AppBar(
title: Text(title),
backgroundColor: scheme.primaryContainer,
foregroundColor: scheme.onPrimaryContainer,
);
}
}Use it as Scaffold(appBar: const BrandBar(title: 'Home'), ...). If you add a bottom to the inner AppBar, update preferredSize to include its height. A wrong value makes the body overlap the bar or leave a gap.
Common errors
- Putting the
AppBarin thebody. It builds, but it is then an ordinary widget. It will not get the status bar padding, and it will not take part in the scaffold's layout. Use theappBarslot. - Passing a non-
PreferredSizeWidgettoappBar. The analyzer reports a type error. Wrap the widget inPreferredSize, or implement the interface. - A wrong
preferredSize. If the number is smaller than what the bar draws, the body overlaps it. Derive the number from the real content rather than guessing. - Expecting a back button after
pushReplacement. Replacing a route leaves nothing under it to return to, so the bar shows no back button. That is correct behavior. - Hard-coded colors on every screen. The bars drift apart over time. Set
appBarThemeonce. - Setting
backgroundColorand forgetting the foreground. A dark background with the default dark title is unreadable. SetforegroundColoras well, or choose a matching pair from theColorScheme, such asprimarywithonPrimary.
Extending the body behind the bar
By default, the body starts at the bottom edge of the bar. If you set extendBodyBehindAppBar: true on the Scaffold and make the bar transparent, the body fills the whole screen and the bar floats over it. This works for image headers. You then have to pad the body yourself so important content isn't hidden under the bar, for example with MediaQuery.paddingOf(context).top + kToolbarHeight.
A bar that scrolls away
Scaffold.appBar holds a bar that is always visible. If the bar should scroll with the content, collapse, or reappear on a scroll back, use a SliverAppBar inside a CustomScrollView in the body. It takes most of the same arguments as AppBar. A later chapter covers it.
Exercise
A screen has a Scaffold with a drawer, and it was opened with Navigator.pushNamed from the home screen. Its AppBar has no leading argument. Which button appears at the start of the bar, and how do you make a back arrow appear instead?
Show answer
A drawer (menu) button appears, because with automaticallyImplyLeading true the bar prefers the drawer over the back button. To get a back arrow, either remove the drawer from that screen or set leading yourself, for example leading: const BackButton(). A manual leading replaces the implied widget.
Exercise
Your Scaffold's appBar is a custom widget that wraps AppBar and sets a TabBar as its bottom. The body now slides under the lower edge of the bar. What is the most likely cause, and what is the fix?
Show answer
The custom widget's preferredSize reports only kToolbarHeight, so the scaffold reserves too little space. Fix it by returning a Size whose height is kToolbarHeight plus the TabBar's height (kTextTabBarHeight for a text-only TabBar).
Exercise
You want every screen's AppBar to have a centered title and a teal background with white text, without repeating arguments. Where do you put this, and what happens if one screen sets its own backgroundColor?
Show answer
Put an AppBarTheme in ThemeData.appBarTheme, with centerTitle: true, backgroundColor set to a teal color, and foregroundColor: Colors.white. An argument on a specific AppBar overrides the theme for that bar only. The other screens keep the themed look.