In some cases, it can be handy to briefly inform our users when certain actionstake place. For example, when a user swipes away a message in a list, we mightwant to inform them the message has been deleted. We might even want to givethem an option to undo the action!
In Material Design, this is the job of aSnackBar.
Directions
- Create a
Scaffold
- Display a
SnackBar
- Provide an additional action
1. Create a Scaffold
When creating apps that follow the Material Design guidelines, we’ll want togive our apps a consistent visual structure. In this case, we’ll need to displaythe SnackBar
at the bottom of the screen, without overlapping other importantWidgets, such as the FloatingActionButton
!
The ScaffoldWidget from thematerial librarycreates this visual structure for us and ensures important Widgets don’toverlap!
Scaffold(
appBar: AppBar(
title: Text('SnackBar Demo'),
),
body: SnackBarPage(), // You'll fill this in below!
);
2. Display a SnackBar
With the Scaffold
in place, you can display a SnackBar
! First, you need tocreate a SnackBar
, then display it using the Scaffold
.
final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));
// Find the Scaffold in the Widget tree and use it to show a SnackBar
Scaffold.of(context).showSnackBar(snackBar);
3. Provide an additional action
In some cases, you might want to provide an additional action to the user whenthe SnackBar is displayed. For example, if they’ve accidentally deleted amessage, we could provide an action to undo that change.
To achieve this, we can provide an additional action
to the SnackBar
Widget.
final snackBar = SnackBar(
content: Text('Yay! A SnackBar!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change!
},
),
);
Complete example
Note: In this example, the SnackBar displays when a user taps on a button. Formore information on working with user input, please see theGestures section of the Cookbook.
import 'package:flutter/material.dart';
void main() => runApp(SnackBarDemo());
class SnackBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SnackBar Demo',
home: Scaffold(
appBar: AppBar(
title: Text('SnackBar Demo'),
),
body: SnackBarPage(),
),
);
}
}
class SnackBarPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
onPressed: () {
final snackBar = SnackBar(
content: Text('Yay! A SnackBar!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change!
},
),
);
// Find the Scaffold in the Widget tree and use it to show a SnackBar!
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('Show SnackBar'),
),
);
}
}