Displaying SnackBars in Flutter: A Step-by-Step Guide with Examples

Learn how to effectively use SnackBars in Flutter for displaying temporary notifications to the user with easy to follow examples and code snippets

What is the SnackBar class?

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.

Notes:

  • Always keep in mind that the SnackBar shouldn’t distract the end user from the main goal of the app.
  • This is one reason why a SnackBar is typically placed at the bottom of the app screen. 
  • The recommended duration for a SnackBar to display in a Flutter app is 4 to 10 seconds — no longer.

  • It’s a good practice to implement some kind of interactive element to accompany your message.
  • For example, you might create an action button with a label such as “Dismiss” or “Try again” and attach it to the SnackBar widget.
..
#1 Custom snackbar:
The code displays a snackbar on the screen. 

The snackbar is created using the SnackBar widget and is displayed using the showSnackBar method of the ScaffoldMessenger widget.

The SnackBar widget is composed of several other widgets such as Card, Container, and Row

The Card widget is used to create a container with a rounded rectangle border. The clipBehavior property is set to Clip.antiAliasWithSaveLayer to create a better looking clip with improved performance.

The Row widget is used to arrange the contents of the snackbar in a horizontal manner. The first child of the Row widget is a SizedBox widget used as a spacer. The second child is an Expanded widget that contains a Column widget which displays the main content of the snackbar, in this case, two texts "Iphone 11" and "Has Been Removed".

The third child of the Row widget is a Container widget that acts as a separator between the content and the action of the snackbar. The SnackBarAction widget is used to display a button labeled "UNDO" on the right side of the snackbar. When the button is pressed, the onPressed property is triggered and the specified function is executed.

The duration property of the SnackBar widget is set to 3 second which means the snackbar will disappear after 3 second. The backgroundColor property is set to transparent so that the snackbar will appear on top of the current content without obscuring it.

 // Showing a snack bar using ScaffoldMessenger
      ScaffoldMessenger.of(_scaffoldCtx).showSnackBar(
        SnackBar(
          // Setting the elevation to 0 to make the snack bar flat
          elevation: 0,
          content: Card(
            // Rounding the border of the card
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
            // Setting the clipping behavior for the card
            clipBehavior: Clip.antiAliasWithSaveLayer,
            elevation: 1,
            child: Container(
              // Adding padding to the container
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              child: Row(
                children: [
                  // Adding space to the left side
                  const SizedBox(width: 5, height: 0),
                  Expanded(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        // Displaying the product name with a bold font
                        TextStyleExample(name : 'Iphone 11',style : textTheme.labelLarge!.copyWith(color: Theme.of(context).colorScheme.primary)),
                        // Displaying the action that has been taken
                        TextStyleExample(name : 'Has Been Removed',style : textTheme.labelSmall!),
                      ],
                    ),
                  ),
                  // Adding a vertical line between the product name and the undo button
                  Container(color: Colors.grey, height: 35, width: 1, margin: const EdgeInsets.symmetric(horizontal: 5)),
                  SnackBarAction(
                    // Displaying the undo button
                    label: "UNDO",
                    textColor: Theme.of(context).colorScheme.primary,
                    // Callback function for when the undo button is pressed
                    onPressed: (){},
                  ),
                ],
              ),
            ),
          ),
          // Setting the background color to transparent
          backgroundColor: Colors.transparent,
          // Setting the duration for how long the snack bar should be visible
          duration: const Duration(seconds: 3),
        ),
      );
..
#2 Custom Snackbar with Image:

This code is a Flutter example that shows how to display a SnackBar with a custom design. The design of the SnackBar is customized by using different widgets to build the content of the SnackBar.

  // Showing a Snackbar with a custom design
      ScaffoldMessenger.of(_scaffoldCtx).showSnackBar(SnackBar(
        // Setting the elevation to 0 to make the Snackbar look flat
        elevation: 0,

        // Content of the Snackbar
        content: Card(
          // Adding a rounded rectangle border to the Snackbar content
          shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5),),

          // Setting the clip behavior for the Snackbar content
          clipBehavior: Clip.antiAliasWithSaveLayer,
          // Adding a small elevation to the Snackbar content to give it a raised effect
          elevation: 1,

          // The main container for the Snackbar content
          child: Container(
            // Adding padding to the container
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
            // A row widget to arrange the content inside the container
            child: Row(
              children: [
                // Adding a spacer with a width of 5
                const SizedBox(width: 5, height: 0),
                // Adding an image asset of the chat icon
                Image.asset(Img.get('chat.png'),
                  height: 40, width: 40,
                ),
                // Adding a spacer with a width of 10
                const SizedBox(width: 10, height: 0),
                // A column widget to arrange the text content
                Expanded(child: Column(
                  // Setting the main axis size to minimum
                  mainAxisSize: MainAxisSize.min,
                  // Aligning the content to the start of the column
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    // Displaying the name of the item "Black-forest" with a custom style
                    TextStyleExample(name : 'Iphone 11',style : textTheme.labelLarge!.copyWith(color: Theme.of(context).colorScheme.primary)),
                    // Show the text "Has Been Removed" with a caption style
                    TextStyleExample(name : 'Has Been Removed',style : textTheme.labelSmall!.copyWith(color: Theme.of(context).colorScheme.primary)),
                  ],
                )),
                // Adding a separator line with a color of Colors.grey
                Container(color: Colors.grey, height: 35, width: 1, margin: const EdgeInsets.symmetric(horizontal: 5)),
                // Adding an undo button
                SnackBarAction(
                  // Setting the label for the undo button
                  label: "UNDO",
                  // Setting the text color for the undo button
                  textColor: Colors.black,
                  // Setting the callback function for when the undo button is pressed
                  onPressed: (){},
                )
              ],
            ),
          ),
        ),
        // Setting the background color of the Snackbar to be transparent
        backgroundColor: Colors.transparent,
        // Setting the duration for how long the Snackbar will be displayed
        duration: const Duration(seconds: 3),
      ));
..

#3 Simple Snackbar:
How to display a SnackBar. A SnackBar is a lightweight message that briefly informs the user of some operation result. The SnackBar contains a message (content) and an optional action.

In this example, the SnackBar is created with the content "Yay! A SnackBar!" and an action "Undo". The SnackBar is then displayed by using the ScaffoldMessenger widget, which is a utility widget that provides a simple way to display SnackBars at the bottom of the screen. The ScaffoldMessenger.of(context) method is used to find the ScaffoldMessenger widget in the widget tree and the showSnackBar method is used to display the SnackBar.

When the SnackBar is displayed, the action "Undo" will be displayed in the SnackBar and can be pressed by the user. When the action is pressed, the onPressed callback will be called and any code inside the callback will be executed.

Here’s an example of providing an additional action to the SnackBar widget:

    // Create a SnackBar widget
      final snackBar = SnackBar(
        // The text to display in the SnackBar
        content: const Text('Yay! A SnackBar!'),
        // The action to display in the SnackBar
        action: SnackBarAction(
          // The label for the action button
          label: 'Undo',
          // Callback function to be executed when the action button is pressed
          onPressed: () {
            // Some code to undo the change.
          },
        ),
      );

      // Find the ScaffoldMessenger in the widget tree
      // and use it to show the SnackBar.
      // The _scaffoldCtx variable holds the context of the Scaffold widget
      ScaffoldMessenger.of(_scaffoldCtx).showSnackBar(snackBar);

..

..

GET source code on Github:

..

Comments