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-
- 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)
- Create a SnackBar – We pass a content parameter to the SnackBar. Content is the message that you want to display.
- Provide an action(optional) – We use the action parameter of the SnackBar to set the action (like Undo action).
- Show the SnackBar using ScaffoldMessenger
Now let’s see an example –
(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.
That’s all about SnackBar in flutter.