Snackbar in Flutter
Introduction
Snackbar is a lightweight message bar displayed at the bottom of the screen. It is used to show short notifications like saved or deleted and lets users perform actions such as undo or retry.
Example 1: Simple Snackbar
In this example below, you will create a simple Snackbar that displays a message This is a Snackbar! when a button is pressed.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('This is a Snackbar!'),
),
);
Example 2: Snackbar with Action
In this example below, you will create a Snackbar with an action that allows the user to undo an operation.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Message deleted'),
action: SnackBarAction(
label: 'UNDO',
onPressed: () {
// Perform some action
},
),
),
);
Example 3: Customized Snackbar
In this example below, you will create a Snackbar with a custom background color.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('This is a custom Snackbar!'),
backgroundColor: Colors.blue,
),
);
Example 4: Snackbar with Duration
In this example below, you will create a Snackbar that disappears after 3 seconds.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('This message will disappear after 3 seconds'),
duration: Duration(seconds: 3),
),
);
Challenge
Create a Snackbar that displays a message Account created successfully when a user press Register button. The Snackbar should have a green background and disappear after 5 seconds.
MaterialButton(
onPressed: () {
// your code here
},
child: Text('Register'),
)