Sub topic 10
Showing SnackBars with ScaffoldMessenger
This chapter assumes you can write a StatelessWidget and a StatefulWidget. It also assumes you know how a Scaffold sits under a MaterialApp, and you can read Dart Future and async code. You will learn what a SnackBar is, why a separate object (ScaffoldMessenger) shows it, how SnackBars queue and close, and which mistakes cause runtime errors.
What a SnackBar is for
A SnackBar is a short message that appears at the bottom of the screen and goes away by itself. Use it for brief feedback about something that already happened: "Message archived", "Saved", "Could not connect". It can carry one action button, such as Undo.
A SnackBar is not a place for important information. The user may never look at it, and it disappears after a few seconds. For decisions or errors that block the user, use a dialog or put the message in the screen itself.
The basic call
SnackBar is only the description of the message: its content, duration and action. ScaffoldMessenger is the object that displays it. You get the messenger from the widget tree and pass it a SnackBar:
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Compose tapped')),
);ScaffoldMessenger.of(context) looks up the tree from context until it finds a ScaffoldMessenger. MaterialApp creates one for you near the root of the app, so every screen below MaterialApp can find it. The context you pass must therefore be a descendant of MaterialApp. The build method of any screen satisfies that.
Why a messenger and not the Scaffold
Older Flutter code called Scaffold.of(context).showSnackBar(...). That was removed because it tied the message to one particular Scaffold. The two problems were:
- If the screen that showed the message was popped, the message vanished with it.
- You needed a
contextthat was below theScaffold, which usually forced an extraBuilderwidget.
ScaffoldMessenger sits above all the Scaffolds in the app. It owns the queue of SnackBars and tells whichever Scaffold is currently visible to draw the current one. The Scaffold is only the place where the message is drawn.
Because the messenger lives above the Scaffolds, a SnackBar can outlive the screen that created it. If you show a SnackBar and then call Navigator.pop, the message carries over to the Scaffold of the screen you return to. This is intended. It lets "Item deleted" appear after a detail screen closes.
Where the SnackBar appears
The Scaffold positions the SnackBar above the bottom navigation bar and pushes the floatingActionButton up so it is not covered. By default the bar is fixed to the bottom edge and spans the full width.
With behavior: SnackBarBehavior.floating, the SnackBar becomes a rounded card with margins that hovers above the content. It then sits above the floating action button, not under it.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text('Draft saved'),
behavior: SnackBarBehavior.floating,
duration: const Duration(seconds: 3),
showCloseIcon: true,
),
);The common properties are listed here.
| Property | Purpose |
|---|---|
| `content` | Any widget, usually a `Text`. |
| `duration` | How long the message stays. The default is four seconds. |
| `action` | A `SnackBarAction` with a label and a callback. |
| `behavior` | `fixed` (default) or `floating`. |
| `showCloseIcon` | Shows an icon the user taps to dismiss it. |
| `backgroundColor` | Overrides the theme color for this message only. |
If you set nothing, the colors come from the app theme, so the SnackBar follows your ColorScheme in light and dark mode.
Adding an action
A SnackBarAction adds a text button to the right of the message. The classic use is undo:
SnackBar(
content: const Text('Message archived'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// restore the message here
},
),
)Tapping the action runs onPressed and dismisses the SnackBar. A SnackBar can hold only one action. If you need more choices, you need a different widget.
Queueing, hiding, and clearing
showSnackBar does not replace the message on screen. It adds the new SnackBar to a queue. If a user taps a button five times, five SnackBars show one after another, each for its full duration. That feels broken to users.
The usual fix is to remove the current message before showing the next one:
final messenger = ScaffoldMessenger.of(context);
messenger
..hideCurrentSnackBar()
..showSnackBar(const SnackBar(content: Text('Saved')));The messenger has several methods for managing the queue.
| Method | Effect |
|---|---|
| `hideCurrentSnackBar()` | Plays the exit animation for the current SnackBar. The next queued one then appears. |
| `removeCurrentSnackBar()` | Removes the current one immediately, with no animation. |
| `clearSnackBars()` | Removes the current one with the exit animation and drops everything queued. |
For the "replace the message" behavior, use hideCurrentSnackBar() before showSnackBar. Use clearSnackBars() when a screen change makes every pending message irrelevant.
Knowing how it closed
showSnackBar returns a ScaffoldFeatureController<SnackBar, SnackBarClosedReason>. Its closed property is a Future that completes when the SnackBar goes away, and it tells you why. This is how you finalize an action only if the user did not tap Undo.
final controller = ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text('Item deleted'),
action: SnackBarAction(label: 'Undo', onPressed: () {}),
),
);
controller.closed.then((reason) {
if (reason != SnackBarClosedReason.action) {
// The user did not undo, so the delete can become permanent.
}
});The SnackBarClosedReason values are:
action: the user tapped the action button.dismiss: the user dismissed it, for example with the close icon.swipe: the user swiped it away.hide: your code calledhideCurrentSnackBar.remove: your code calledremoveCurrentSnackBarorclearSnackBars.timeout: the duration ran out.
The controller also has close(), which closes that one SnackBar, and setState, which rebuilds it. Use close() when you keep the controller and want to dismiss a specific message later.
A complete example: delete with undo
This app lists items. Swiping or tapping delete removes an item and shows a SnackBar with Undo. It runs as shown.
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: 'Snack demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
home: const ItemsPage(),
);
}
}
class ItemsPage extends StatefulWidget {
const ItemsPage({super.key});
@override
State<ItemsPage> createState() => _ItemsPageState();
}
class _ItemsPageState extends State<ItemsPage> {
final List<String> _items = List.generate(5, (i) => 'Item $i');
void _delete(int index) {
final removed = _items[index];
setState(() => _items.removeAt(index));
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text('$removed deleted'),
behavior: SnackBarBehavior.floating,
action: SnackBarAction(
label: 'Undo',
onPressed: () {
setState(() => _items.insert(index, removed));
},
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Items')),
body: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) => ListTile(
title: Text(_items[index]),
trailing: IconButton(
icon: const Icon(Icons.delete),
tooltip: 'Delete',
onPressed: () => _delete(index),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(content: Text('${_items.length} items')),
);
},
child: const Icon(Icons.info_outline),
),
);
}
}Two details matter here. The context used in _delete is the State's context, which is below MaterialApp, so the lookup succeeds. The Undo callback uses setState on the same State object, so it works as long as that screen is still mounted. If the user leaves the screen before tapping Undo, the callback would call setState on a disposed object. Guard against that in real code with if (!mounted) return;.
Using the messenger across an async gap
SnackBars are often shown after an await, for example after a network call. Using a BuildContext after an await is risky, because the widget may have been removed while you waited. Flutter's analyzer reports this as use_build_context_synchronously.
The standard fix is to check mounted before touching the context:
Future<void> _save() async {
await Future<void>.delayed(const Duration(seconds: 1)); // stands in for a request
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Saved')),
);
}A second option is to capture the messenger before the await. This works even if the widget is gone afterward, and the message still shows on whatever screen is visible:
Future<void> _save() async {
final messenger = ScaffoldMessenger.of(context);
await Future<void>.delayed(const Duration(seconds: 1));
messenger.showSnackBar(const SnackBar(content: Text('Saved')));
}Pick the second form when the message should appear even if the user has navigated away, such as "Upload finished". Pick the first when the message only makes sense on this screen.
Showing messages from outside the widget tree
Sometimes code has no BuildContext: a repository class, a background listener, an error handler. In that case give MaterialApp a GlobalKey<ScaffoldMessengerState> through its scaffoldMessengerKey parameter and use the key instead of of(context):
import 'package:flutter/material.dart';
final messengerKey = GlobalKey<ScaffoldMessengerState>();
void main() => runApp(
MaterialApp(
scaffoldMessengerKey: messengerKey,
home: Scaffold(
appBar: AppBar(title: const Text('Key demo')),
body: Center(
child: ElevatedButton(
onPressed: () => notify('Hello from anywhere'),
child: const Text('Notify'),
),
),
),
),
);
void notify(String text) {
messengerKey.currentState?.showSnackBar(SnackBar(content: Text(text)));
}currentState is null until the app has built, so use ?. as shown. Keep this as an exception, not the default. A key makes it easy to show messages from places that have no idea which screen is visible, and that can produce confusing UX.
Common errors
- "No ScaffoldMessenger widget found." You called
ScaffoldMessenger.of(context)with a context that is not below aMaterialApp. This happens if you call it inmainor in a widget built aboveMaterialApp. Move the call into a screen, or usescaffoldMessengerKey. - A stack of repeated messages. Each tap queues another SnackBar. Call
hideCurrentSnackBar()first. - Message appears on the wrong screen. The messenger is app-wide, so a SnackBar shown before navigation appears on the next screen. Call
clearSnackBars()in the code that leaves the screen if you do not want that. - Undo does nothing, or throws. The callback ran after the screen was disposed. Check
mountedbeforesetState. - FAB hidden by a floating SnackBar. With
behavior: SnackBarBehavior.floating, a SnackBar with a custommargincan overlap the FAB. Prefer the default margin, or leave room for the FAB. - Unreadable text in dark mode. You set
backgroundColorto a fixed color. Leave it unset so the theme chooses.
Exercise
A "Save" button calls an async function, awaits a network request, and then shows a SnackBar with ScaffoldMessenger.of(context). The analyzer warns about using BuildContext across an async gap. Give two ways to fix it and say when you would choose each.
Show answer
Fix 1: after the await, add if (!mounted) return; before using context. Choose this when the message only makes sense on this screen. Fix 2: read final messenger = ScaffoldMessenger.of(context); before the await and call messenger.showSnackBar(...) afterward. Choose this when the message should still appear even if the user has left the screen, because the messenger belongs to the app and not to this widget.
Exercise
A user taps a button three times quickly. Three SnackBars show one after another, which is annoying. What is the smallest change that shows only the latest message, and what is the difference between hideCurrentSnackBar() and clearSnackBars()?
Show answer
Call ScaffoldMessenger.of(context).hideCurrentSnackBar() before showSnackBar. This hides the one on screen with its exit animation, so the new one replaces it. clearSnackBars() also drops every SnackBar still waiting in the queue, while hideCurrentSnackBar() only closes the current one and lets the next queued one appear.
Exercise
You delete an item and show a SnackBar with an Undo action. Using the closed future, how do you run the permanent delete only when the user did not tap Undo?
Show answer
Keep the controller returned by showSnackBar and call controller.closed.then((reason) { if (reason != SnackBarClosedReason.action) { /* delete permanently */ } });. The reason is action only when the user tapped Undo. Any other reason (timeout, dismiss, swipe, hide, remove) means the delete should go ahead.