How to create snackbar in flutter?

One of the ways to enhance user experience is to inform the user with a brief message when certain actions take place. SnackBar is the one that we can use to greatly enhance the user experience. One of its features that I like the most is adding an action with it. It really helps when your app’s user accidentally performs an action that they didn’t want to, at least they have an option to undo the action, they can simply tap on the undo button that the snackbar provides. In this post, we are going to see how to create a snackbar in flutter. So, let’s begin.

(In case you don’t know what a snackbar is, then click here to get the answer.)

To use a SnackBar in your flutter project, just follow these steps-

  1. Create a Scaffold – We create a snackbar inside Scaffold because Scaffold ensures that important widgets don’t overlap(For example- you might overlap the FloatingActionButton if you don’t use the scaffold)
  2. Create a SnackBar – We pass a content parameter to the SnackBar. Content is the message that you want to display.
  3. Provide an action(optional) – We use the action parameter of the SnackBar to set the action (like Undo action).
  4. Show the SnackBar using ScaffoldMessenger

Now let’s see an example –

class SnackBarRoute extends StatelessWidget {
const SnackBarRoute({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
//Create the SnackBar
final snackBar = SnackBar(
content: const Text('Hi there! I am a snackbar.'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Place the code to undo the change.
},
),
);
// Use ScaffoldMessenger to show the SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
child: const Text('Show SnackBar'),
),
);
}
}

(View full code –Click here)

You can see in the above code that I have created a SnackBar, added an undo button as an action, and as the last step, I have used ScaffoldMessenger to display the SnackBar.

Output:

That’s all about SnackBar in flutter.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: