DEV Community

Afolayan Ademola Segun
Afolayan Ademola Segun

Posted on

How To Display A SnackBar In Flutter

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 can be useful 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.

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(),
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

And that's a wrap. Shikena🤗 (that's all). I hope this article has been able to enlighten you and make building awesome, beautiful, and useful apps.

If you would like to discuss this or any related issueChat Me. Follow me on Twitter for More...

Top comments (0)