How to show SnackBar aka Toast in Flutter

Share this post

One of the very useful Material widgets is SnackBar. SnackBar helps you with showing a brief message to your user as feedback to some action they have taken. For example, after a user has a deleted an email or created a new to-do item in a certain app.

The basic use of SnackBar is very simple. Let’s see how it works when we just want to show a user that a certain action was successful:

First we start by defining our SnackBar and the options:

final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));

What’s important is that we need to use Scaffold on our page. Scaffold makes our life easier by taking care of SnackBar not overlapping any important other widgets, like FloatingActionButton.

So let’s trigger our SnackBar:

final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));

  @override
  Widget build(BuildContext context) {
    final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));

    return Scaffold(
      appBar: AppBar(
        title: Text('MrFlutter'),
      ),
      body: Container(
        child: ElevatedButton(
          onPressed: () => ScaffoldMessenger.of(context).showSnackBar(snackBar),
          child: Text('SnackBar'),
        ),
      ),
    );
  }

How you use SnackBar with action

Let’s say we want to perform a certain action when we tap a SnackBar. For instance, when we want to undo the action we just performed or dismiss the SnackBar. We just need to pass an action to our SnackBar widget:

final snackBar = SnackBar(
      content: Text('Email deleted'),
      action: SnackBarAction(
        label: 'Undo',
        onPressed: () {
          // Undo action here
        },
        // textColor: ,  Color for undo button
        // disabledTextColor: , Color when undo button is disabled
      ),
    );

Define how long SnackBar is shown

To define how long it should take for the SnackBar message to disappear, we need to use the duration property. Let’s say we want the message to show for 5 seconds. This is how we do it:

final snackBar = SnackBar(
      content: Text('Email deleted'),
      action: SnackBarAction(
        label: 'Undo',
        onPressed: () {},
      ),
      duration: Duration(seconds: 5),
    );

We have discussed already how we can show a SnackBar, defined the content (could be any Widget), defined the action, and finally defined how to set how long to show a SnackBar. There are more ways to customize a SnackBar in Flutter. In my next post, I will show you in detail how we can customize a SnackBar, like animation, colors, shape, and behavior.