Sub topic 10
Showing SnackBars with ScaffoldMessenger
This chapter assumes that you know basic Dart syntax, can run a Flutter app, and understand StatelessWidget, StatefulWidget, and the build method. It also assumes that you know a screen normally uses a Scaffold with an AppBar and a body.
A SnackBar is a short message that appears temporarily near the bottom of the screen. It gives feedback after an action, such as saving a form, copying text, or adding an item. A SnackBar is not a dialog. It does not block the rest of the screen, and it normally disappears without user input.
How ScaffoldMessenger fits into the widget tree
ScaffoldMessenger is a widget that manages SnackBars for one or more Scaffold widgets. A MaterialApp provides a root ScaffoldMessenger automatically, so most applications can show a SnackBar without adding one manually.
Call ScaffoldMessenger.of(context) to find the nearest messenger associated with the current widget tree. Then call showSnackBar with a SnackBar object.
flowchart TD
A[MaterialApp] --> B[ScaffoldMessenger]
B --> C[Scaffold]
C --> D[AppBar]
C --> E[Body]
C --> F[FloatingActionButton]
F --> G[showSnackBar]
G --> BThe BuildContext used in the call must be below a ScaffoldMessenger. A button inside a screen's Scaffold usually meets this requirement.
Showing a basic SnackBar
The following app displays a SnackBar when the floating action button is pressed.
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: 'SnackBar Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
home: const HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
void _showSavedMessage(BuildContext context) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Message saved'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Inbox'),
),
body: const Center(
child: Text('Your messages appear here'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _showSavedMessage(context),
child: const Icon(Icons.save),
),
);
}
}The button's callback receives no context directly. The callback closes over the BuildContext passed to build. The helper method then finds the messenger and queues the SnackBar.
Controlling duration and actions
A SnackBar stays visible for a default period. Set duration when the message needs more or less time. You can also add an action, such as UNDO.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text('Item deleted'),
duration: const Duration(seconds: 5),
action: SnackBarAction(
label: 'UNDO',
onPressed: () {
// Restore the deleted item.
},
),
),
);The SnackBarAction callback should perform the related operation. Do not use the action only to dismiss the message. The message already disappears after its duration.
If a new SnackBar should replace the current one immediately, hide the current SnackBar first:
final messenger = ScaffoldMessenger.of(context);
messenger
..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(content: Text('New status')),
);The .. syntax is Dart's cascade notation. It calls multiple methods on the same messenger object.
Common errors
Looking up the messenger with the wrong context
A context above MaterialApp cannot find the root ScaffoldMessenger. This often happens when a global builder or a custom service tries to show a SnackBar without receiving a screen context.
Prefer calling the messenger from a widget callback. If application-wide code must display messages, pass a GlobalKey<ScaffoldMessengerState> to MaterialApp.scaffoldMessengerKey and use that key deliberately.
Showing messages after a screen is disposed
An asynchronous operation can finish after its screen has been removed. In a State object, check mounted before using its context:
if (!mounted) {
return;
}
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Upload complete')),
);This prevents a callback from updating a widget that is no longer in the tree.
Creating a separate messenger unnecessarily
A nested ScaffoldMessenger creates a separate scope. That can be useful for an isolated section, but it can also make a SnackBar appear in an unexpected place. Start with the messenger supplied by MaterialApp, and add a nested one only when you need separate SnackBar behavior.
Exercise
Why does a button inside a Scaffold normally use ScaffoldMessenger.of(context) instead of Scaffold.of(context) to show a SnackBar?
Show answer
ScaffoldMessenger manages SnackBars across Scaffold widgets, while Scaffold.of(context) only finds a Scaffold and does not provide the SnackBar API.