Sub topic 3
Scaffold: the structure of a screen
This chapter covers what Scaffold provides, how its slots are laid out, and where it sits in the widget tree. It also covers the mistakes that most often trip people up. It assumes you can read basic Dart (classes, constructors, named parameters), can run a Flutter app, and know how StatelessWidget and build work. The previous chapter covered MaterialApp, so this one starts one level below it, at the screen.
What Scaffold is for
MaterialApp configures the whole app: theme, routes, and the navigator. It does not decide what one screen looks like. Scaffold does that job. It is a widget that arranges a Material screen into named slots: a top bar, a main content area, a floating button, side panels, and a bottom bar. You hand each slot a widget, and Scaffold positions it.
Doing this by hand would mean writing a Stack, measuring the status bar, tracking the keyboard, and animating drawers yourself. Scaffold handles those details. It also does three things you can't see in the code:
- It paints the screen background, using
ThemeData.scaffoldBackgroundColorunless you setbackgroundColor. - It inserts a
Materialancestor, so ink effects such asListTileripples have something to draw on. - It acts as the anchor for the drawer, bottom sheets, and snack bars.
Most screens in a Material app have exactly one Scaffold as the root of their build method.
Where Scaffold sits in the tree
A typical screen nests like this:
MaterialApp is created once. Each screen is its own widget class (HomePage here) whose build returns a Scaffold. When you push a new route, the navigator builds a new screen widget with its own Scaffold on top of the old one. That is why every screen gets its own app bar and its own floating action button.
A Scaffold with several slots
This is a complete app that fills five slots. Run it and compare each line of code with what appears on 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: 'Slots',
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('Slots')),
drawer: const Drawer(child: Center(child: Text('Drawer'))),
body: const Center(child: Text('Body')),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: const Icon(Icons.add),
),
bottomNavigationBar: const BottomAppBar(
child: Center(child: Text('Bottom bar')),
),
);
}
}Every parameter is optional. A Scaffold() with no arguments is valid and shows an empty background. You only fill the slots a screen needs.
The slots
| Parameter | Type | Where it appears |
|---|---|---|
| `appBar` | `PreferredSizeWidget?` | Top edge, usually an `AppBar` |
| `body` | `Widget?` | Main area, below the app bar and above the bottom bar |
| `floatingActionButton` | `Widget?` | Floats over the body, bottom right by default |
| `floatingActionButtonLocation` | `FloatingActionButtonLocation?` | Moves the button, for example `centerDocked` |
| `drawer` | `Widget?` | Panel that slides in from the leading edge |
| `endDrawer` | `Widget?` | Panel that slides in from the trailing edge |
| `bottomNavigationBar` | `Widget?` | Bottom edge, outside the body area |
| `bottomSheet` | `Widget?` | Persistent panel above the bottom bar |
| `persistentFooterButtons` | `List<Widget>?` | Row of buttons just above the bottom bar |
| `backgroundColor` | `Color?` | Screen background |
The type of appBar matters. It is PreferredSizeWidget, not Widget, because Scaffold needs to know the bar's height before it lays out the body. AppBar implements that interface. A plain Container does not, so you can't pass one directly. If you want a custom bar, wrap it in PreferredSize(preferredSize: Size.fromHeight(64), child: ...).
The next chapters cover the app bar, the body and floating action button, the drawer, and snack bars in detail. Here the goal is to understand the container that holds them.
How Scaffold lays things out
The layout rules explain most surprising behavior, so they are worth stating exactly.
- The app bar takes its preferred height from the top. The status bar area is included in that height, so the bar draws behind the system status icons with its own padding.
- The bottom navigation bar takes its height from the bottom.
- The body gets the remaining space, as tight constraints. A body that is a
Center,Column, orListViewfills that rectangle. - The floating action button, drawers, and bottom sheet are drawn over the body in a layered stack.
Scaffold also adjusts the MediaQuery padding it passes to the body. When an app bar is present, the top inset is already consumed, so a SafeArea inside the body does not add space twice. When there is no app bar, nothing consumes the status bar inset, and the body starts at the very top of the screen. In that case, wrap the content in a SafeArea yourself.
Extending the body behind bars
Sometimes you want content to show through the bars, for example a photo behind a transparent app bar. Two flags control this:
extendBodyBehindAppBar: truemakes the body start at the top of the screen instead of below the app bar.extendBody: truemakes the body continue behind the bottom navigation bar or bottom app bar.
import 'package:flutter/material.dart';
class GradientPage extends StatelessWidget {
const GradientPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
scrolledUnderElevation: 0,
title: const Text('Photo'),
),
body: const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.teal, Colors.indigo],
),
),
child: SizedBox.expand(),
),
);
}
}With these flags on, the first widgets in the body can sit under the bar and be hidden by it. The body's MediaQuery padding then includes the bar's height, so use MediaQuery.paddingOf(context).top or a SafeArea to push the content down when you need to.
Keyboard behavior
resizeToAvoidBottomInset defaults to true. When the on-screen keyboard opens, Scaffold shrinks the body by the keyboard height, and the floating action button moves up with it. A screen with a TextField near the bottom therefore stays visible without extra code.
The side effect is that the body is laid out again with less height. A body with a fixed-size Column can overflow and show the yellow and black overflow stripes. There are two fixes:
- Make the body scrollable, for example a
SingleChildScrollVieworListView. This is usually the right choice. - Set
resizeToAvoidBottomInset: falsewhen the layout should stay put, such as a screen with a background image that must not squash. Fields under the keyboard are then your responsibility.
Reaching the Scaffold from inside it
Scaffold.of(context) returns the ScaffoldState of the nearest Scaffold above context. Through it you can call openDrawer(), openEndDrawer(), and showBottomSheet().
The word "above" is the source of the most common error. In the screen's own build method, the context belongs to the screen widget. That widget is the parent of the Scaffold you are creating in the same method, so no Scaffold is above it yet. Calling Scaffold.of(context) there throws a FlutterError that says the context does not contain a Scaffold.
The fix is to get a context from a widget that is below the Scaffold. A Builder gives you one:
import 'package:flutter/material.dart';
class MenuPage extends StatelessWidget {
const MenuPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Menu demo')),
drawer: const Drawer(child: Center(child: Text('Menu'))),
body: Center(
child: Builder(
builder: (innerContext) => FilledButton(
onPressed: () => Scaffold.of(innerContext).openDrawer(),
child: const Text('Open menu'),
),
),
),
);
}
}Here innerContext belongs to the widget returned inside Builder, which sits below the Scaffold, so the lookup succeeds. Splitting the button into its own widget class works the same way, because that class gets its own build and its own context. If a Scaffold might legitimately be missing, use Scaffold.maybeOf(context), which returns null instead of throwing.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Text has a yellow double underline and no Material styling | The screen has no `Scaffold` (or other `Material`) above its text | Return a `Scaffold` from the screen's `build` |
| `Scaffold.of() called with a context that does not contain a Scaffold` | `context` is above the `Scaffold`, usually the screen's own context | Use a `Builder`, or move the caller into a child widget |
| Content hidden under the status bar | No app bar, and no `SafeArea` | Wrap the body in `SafeArea` |
| Overflow stripes when the keyboard opens | A fixed-height body is shrunk by `resizeToAvoidBottomInset` | Make the body scrollable |
| Two app bars on one screen | A `Scaffold` is nested inside another one's body, and both set `appBar` | Give only one `Scaffold` an `appBar`, or remove the inner `Scaffold` |
| Back button missing | The screen is the first route on the stack | Expected; the back button appears only when there is a route to return to |
Nesting Scaffolds
Nesting a Scaffold inside another Scaffold's body is legal, and some apps do it on purpose. A common case is a root screen that owns a drawer and bottom navigation, with each tab being a screen that has its own app bar. The rule is to decide which Scaffold owns which slot. If the outer one has an appBar and the inner one does too, you get two bars. If you call Scaffold.of(context) from inside the inner body, you reach the inner one, not the outer one. When a tab needs the outer drawer, hold a GlobalKey<ScaffoldState> on the outer Scaffold and call openDrawer() through it.
Use nesting only when you have a clear reason. For most apps, one Scaffold per route is easier to reason about.
Review
Scaffold is the screen-level layout widget. MaterialApp sits above it and supplies the theme, navigator, and messenger. The Scaffold gives its children a background, a Material surface, and the slots for the bars, body, button, and panels. Keep these points in mind:
- Return one
Scaffoldfrom each screen'sbuild. appBarmust be aPreferredSizeWidget.- The body gets the space left after the bars. Add
SafeAreawhen there is no app bar. Scaffold.ofneeds a context below theScaffold.- Make the body scrollable if the keyboard may cause overflow.
Exercise
A screen's build method returns a Scaffold whose body contains a Text widget. An IconButton in the app bar calls Scaffold.of(context).openEndDrawer(), using the context passed to the screen's build method. The app throws an error when the button is tapped. Why does it fail, and what is the smallest change that fixes it?
Show answer
The context passed to build belongs to the screen widget, which is the parent of the Scaffold created in that same method. No Scaffold exists above that context, so Scaffold.of throws. Wrap the IconButton in a Builder and use the builder's context, for example Builder(builder: (innerContext) => IconButton(icon: const Icon(Icons.menu), onPressed: () => Scaffold.of(innerContext).openEndDrawer())). Moving the button into its own widget class also works. The Scaffold also needs an endDrawer for the drawer to appear.
Exercise
You build a login screen with a Scaffold, no app bar, and a body that is a Column with two TextFields and a button. On a small phone the status icons overlap the first field, and when the keyboard opens the screen shows overflow stripes. Name the two changes you would make and the Scaffold behavior behind each problem.
Show answer
Wrap the body in SafeArea, because without an app bar nothing consumes the top status bar inset and the body starts at the screen's top edge. Make the body scrollable, for example by putting the Column inside a SingleChildScrollView, because resizeToAvoidBottomInset defaults to true and shrinks the body by the keyboard height, which overflows a fixed-height Column. Setting resizeToAvoidBottomInset to false would remove the shrinking, but it would leave the fields hidden under the keyboard.