DEV Community

Thibault
Thibault

Posted on • Updated on

Persisting flutter SnackBar until user interacts with it

On today's "What did i want to achieve/how i achieved it", i wanted to
Show a SnackBar until a user interacts with it.

How i achieved it

Flutter's SnackBar as described on its official documentation; is

A lightweight message with an optional action which briefly displays at the bottom of the screen.

It comes with a duration property that allows you to set how long you want the SnackBar to be visible. Values can be seconds, minutes, hours, days, etc...

Point is, There's no way to tell when the user will interact with it. Leaving me with the only option of setting a longer duration(read days) and hoping the user will interact with it within that time. Only then, it can disappear from the list of widgets.

Key points being:

  • Setting a long duration

    duration: Duration(days: 1)
    
  • Hiding the SnackBar when there's an interaction

    Scaffold.of(context).hideCurrentSnackBar();
    

Below is the code for the SnackBar widget. I'm using a ListTile widget but anything with a callback would do:

SnackBar sb = SnackBar(
  duration: Duration(days: 1),
  content: ListTile(
    onTap: () {
      Scaffold.of(context).hideCurrentSnackBar();
    },
    title: Text(
      "This is a title",
      style: TextStyle(
          fontSize: 24.0,
          fontWeight: FontWeight.bold),
    ),
    subtitle: Text(
        "and i'm a subtitle"),
    trailing: Icon(Icons.check),
  );
);
_scaffoldKey.currentState.showSnackBar(sb);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)