Sub topic 6
Filling the Scaffold: body and floating action button
This chapter assumes you can run a Flutter app, write a StatelessWidget, and read basic Dart (named parameters, closures, const constructors). It also assumes you have seen MaterialApp and a Scaffold with an AppBar. Here you will fill the two slots that do most of the work on a screen: body and floatingActionButton.
What the Scaffold gives you
A Scaffold is a layout widget with named slots. You pass widgets to the slots, and the Scaffold decides where each one goes and how they avoid each other. The slots in this chapter are:
appBar: the top bar.body: the main content, which fills the space left over.floatingActionButton: a round button that floats above the body, in the bottom-right corner by default.
The Scaffold also provides the surface color from the current theme, so you rarely need to set a background yourself.
The body slot
body accepts any widget. The simplest body is a centered message:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: EmptyInbox()));
class EmptyInbox extends StatelessWidget {
const EmptyInbox({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inbox')),
body: const Center(child: Text('No messages')),
);
}
}Center places its child in the middle of the space the Scaffold gives the body. That space is the screen minus the app bar, and minus any system areas such as the status bar.
How the body is sized
The Scaffold gives the body tight constraints: the body must be exactly as wide and tall as the remaining area. Two consequences follow.
- If you pass a widget that wants to be small, such as a bare
Text, it is still given the full area. It is drawn at the top-left becauseTextaligns itself there. Wrap it inCenterorAlignto move it. - If you pass a
Columnwhose children are taller than the area, Flutter paints a yellow-and-black overflow stripe and logs a "RenderFlex overflowed" error. AColumndoes not scroll.
For content that may be taller than the screen, use a scrolling widget as the body. ListView is the usual choice.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: MessageList()));
class MessageList extends StatelessWidget {
const MessageList({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inbox')),
body: ListView.builder(
itemCount: 40,
itemBuilder: (context, index) => ListTile(
leading: const Icon(Icons.mail_outline),
title: Text('Message $index'),
),
),
);
}
}ListView.builder creates list items only when they scroll into view, so it stays cheap even for a long list.
Padding and safe areas
Inside a Scaffold with an AppBar, the body already starts below the bar, so you do not need a SafeArea for the top. The body can still run under the system navigation bar or a notch at the bottom, depending on the device. When the body is not a scrolling widget, wrap it in SafeArea if content could be hidden. For visual spacing, add Padding around the content, not around the whole Scaffold.
body: const SafeArea(
child: Padding(
padding: EdgeInsets.all(16),
child: Text('Content with margins'),
),
),A ListView handles safe-area padding for you when it is a direct child of the Scaffold body, because it reads the surrounding MediaQuery padding.
The floating action button
A floating action button (FAB) is a round button for the single most important action on the screen. On an inbox that action is "compose". Use one FAB per screen. If you have several equally important actions, a FAB is the wrong control.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: HomePage()));
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Inbox'),
centerTitle: true,
actions: [
IconButton(
icon: const Icon(Icons.search),
tooltip: 'Search',
onPressed: () {},
),
],
),
body: const Center(child: Text('No messages')),
floatingActionButton: FloatingActionButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Compose tapped')),
);
},
child: const Icon(Icons.edit),
),
);
}
}Tapping the button runs onPressed. Here it shows a SnackBar, a short message at the bottom of the screen. A later chapter covers ScaffoldMessenger in detail. For now, note that the context used here belongs to HomePage.build, which sits below the MaterialApp, and that is why ScaffoldMessenger.of(context) can find the messenger.
FAB parameters worth knowing
| Parameter | What it does |
|---|---|
| `onPressed` | The tap callback. If it is `null`, the button is drawn disabled. |
| `child` | The content, usually an `Icon`. |
| `tooltip` | Text shown on long press and read by screen readers. |
| `backgroundColor`, `foregroundColor` | Override the theme colors. Prefer changing the theme instead. |
| `heroTag` | Tag for the transition animation between routes. Must be unique if two FABs are on screen at once. |
| `mini` | Draws a smaller button. |
Always set tooltip on an icon-only button. Without it, a screen reader has nothing meaningful to announce.
Extended FAB
When an icon alone is unclear, use FloatingActionButton.extended. It takes a label and an optional icon.
floatingActionButton: FloatingActionButton.extended(
onPressed: () {},
icon: const Icon(Icons.edit),
label: const Text('Compose'),
),Positioning the FAB
The floatingActionButtonLocation property moves the button. The default is FloatingActionButtonLocation.endFloat, bottom-right. Other common values:
centerFloat: bottom-center, above the bottom edge.centerDockedandendDocked: the button sits on the edge of aBottomAppBar, which you pass to thebottomNavigationBarslot.startFloat: bottom-left.
Scaffold(
appBar: AppBar(title: const Text('Docked FAB')),
body: const Center(child: Text('Body')),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Add',
child: const Icon(Icons.add),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
bottomNavigationBar: const BottomAppBar(
child: SizedBox(height: 48),
),
)The Scaffold animates the FAB when its location changes, and it moves the FAB up when a SnackBar appears so the bar does not cover it.
The FAB floats over the body
The FAB is drawn on top of the body. If the body is a list, the last item can end up hidden under the button, and the user cannot tap it. The fix is to add bottom padding to the list so the final item can scroll clear of the FAB.
body: ListView.builder(
padding: const EdgeInsets.only(bottom: 88),
itemCount: 40,
itemBuilder: (context, index) => ListTile(title: Text('Message $index')),
),A standard FAB is 56 logical pixels tall and sits 16 pixels from the edge. A bottom padding of 88 (56 + 16 + 16) clears it.
Making the FAB do something real
Most of the time a FAB opens another screen. Use Navigator.push or a named route:
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.pushNamed(context, '/compose'),
tooltip: 'Compose',
child: const Icon(Icons.edit),
),Named routes were introduced earlier in the plan and are covered in their own chapter. The point here is that onPressed is an ordinary closure. It can use context from the surrounding build method.
Common errors
"Scaffold.of() called with a context that does not contain a Scaffold"
This appears when you call Scaffold.of(context) using the same context that built the Scaffold. That context sits above the Scaffold, so the lookup fails. Fix it by wrapping the code in a Builder, or by moving the code into its own widget below the Scaffold. ScaffoldMessenger.of(context) does not have this problem, because the messenger lives in MaterialApp, above all Scaffolds. Prefer it for SnackBars.
"No Material widget found" or text with yellow underlines
Text shown outside a Scaffold or Material has no default text style, so Flutter draws it with a yellow double underline. The body of a Scaffold supplies a Material surface, so this error usually means you built a screen without a Scaffold.
Multiple heroes share the same tag
If two screens in a navigation stack both have a default FAB, Flutter can throw "There are multiple heroes that share the same tag within a subtree". Give each FAB a distinct heroTag, or set heroTag: null to disable the transition.
RenderFlex overflowed
A Column in the body overflowed. Wrap the content in SingleChildScrollView, or use a ListView.
Unbounded height
Putting a ListView directly inside a Column in the body throws "Vertical viewport was given unbounded height". The Column gives its children unlimited height, and a ListView tries to be as tall as possible. Wrap the ListView in Expanded:
body: Column(
children: [
const Padding(
padding: EdgeInsets.all(16),
child: Text('Header'),
),
Expanded(
child: ListView.builder(
itemCount: 20,
itemBuilder: (context, i) => ListTile(title: Text('Row $i')),
),
),
],
),The keyboard covers the FAB
When a text field in the body gets focus, the keyboard appears and the Scaffold resizes the body. This is controlled by resizeToAvoidBottomInset, which defaults to true. The FAB then moves up with the body. Setting it to false leaves the body unchanged and the keyboard covers whatever is at the bottom.
Putting it together
The next example combines a scrolling body, a padded list end, an extended FAB, and a SnackBar. It is a complete app you can run.
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: 'Notes',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
home: const NotesPage(),
);
}
}
class NotesPage extends StatelessWidget {
const NotesPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Notes')),
body: ListView.builder(
padding: const EdgeInsets.only(bottom: 88),
itemCount: 25,
itemBuilder: (context, index) => ListTile(
leading: const Icon(Icons.note_outlined),
title: Text('Note ${index + 1}'),
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('New note')),
);
},
icon: const Icon(Icons.add),
label: const Text('New note'),
),
);
}
}Design guidance
- Keep
bodyfocused. If thebuildmethod grows long, move the body into its own widget class, for exampleNotesList. Chapters later in this plan cover how to split an app into files. - Use one FAB for the primary action. Put secondary actions in the
AppBaractions. - Hide or omit the FAB on screens where there is no clear primary action, instead of showing a disabled one.
- Let the theme set FAB colors so all screens match.
Exercise
Your body is a ListView with 30 items and a standard FloatingActionButton in the default location. The last item cannot be tapped because the button covers it. What change fixes this, and why does it work?
Show answer
Add bottom padding to the list, for example padding: const EdgeInsets.only(bottom: 88). The FAB is drawn on top of the body and does not take space from it. Padding adds empty scroll space after the last item, so the user can scroll the item up past the button's 56-pixel height plus its 16-pixel margins.
Exercise
A screen has a Column as its body. The column contains a Text header and then a ListView. Flutter throws "Vertical viewport was given unbounded height". How do you fix it?
Show answer
Wrap the ListView in Expanded. A Column gives its children unbounded height, and a ListView tries to fill all available height. Expanded gives the list the leftover height, which is bounded.
Exercise
You add a FAB to two screens that are both on the navigation stack, and Flutter reports multiple heroes sharing the same tag. Name two ways to resolve it.
Show answer
Give each FAB a unique heroTag value, or set heroTag: null on one or both to turn off the hero transition for that button.