Hi, It's Kest Again And I am about to show you how to display a snackbar in Flutter.
What's a SnackBar anyway? 🤔🤔🤔
A SnackBar is a Flutter widget that enables you to temporarily display a pop-up message in your app. It usually appears at the bottom of the app's screen. It is used to briefly inform your users when certain actions take place.
For example, when a user swipes away a message in a list, you might want to inform them that the message has been deleted. You might even want to give them an option to undo the action.
Here is what a SnackBar looks like:
The Bar below the page with Text Signing in and Welcome back is a SnackBar.
You will be able to display a Snackbar in three easy steps:
Create a Scaffold.
Display a SnackBar.
Provide an optional action.
1. Create a Scaffold
Creating a Scaffold is one of the easiest things to do in Flutter, as a piece of general knowledge,everything in Flutter is a widget.
And Fortunately, it's the same for Scaffold.
The Scaffold widget, from the material library, creates this visual structure and ensures that important widgets don’t overlap.
return MaterialApp(
title: 'SnackBar Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('SnackBar Demo'),
),
body: const SnackBarPage(),
),
);
2. Display A SnackBar
With the Scaffold in place, Its time to Display a Snackbar, you can do that with the code snippets below:
const snackBar = SnackBar(
content: Text('Yay! A SnackBar!'),
);
// Find the ScaffoldMessenger in the widget tree
// and use it to show a SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
Yay!! that's it. It's as easy as that. However if you would like your snackBar to perform more functions other than displaying messages about users actions. You can add other properties to the widget.
3. Provide an optional action
You might want to provide an action to the user when the SnackBar is displayed. For example, if the user accidentally deletes a message, they might use an optional action in the SnackBar to recover the message.
Here’s an example of providing an additional action to the SnackBar widget:
final snackBar = SnackBar(
content: const Text('Yay! A SnackBar!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// Some code to undo the change.
},
),
);
And that's a wrap. Shikena 🤗 (that's all). I hope this article has been able to enlighten you and make it easy to build awesome, beautiful, and useful apps.
If you would like to discuss this or any related issue Chat Me. Follow me on Twitter for More...