A Quick Guide To Snack Bar In Flutter – Hupen Design

A Quick Guide To Snack Bar In Flutter – Hupen Design

A Quick Guide To Snack Bar In Flutter – Hupen Design
Published At By Hupen Pun

Snackbars are a lightweight and convenient way to provide feedback to users in Flutter. They are short messages that appear at the bottom of the screen and disappear automatically after a short duration. Snackbars are used to show short, non-interruptive, and temporary messages.

To create a snackbar in Flutter, you need to import the Scaffold widget from the flutter material library and use the Scaffold.of method to access the nearest scaffold in the widget tree.

Here’s how you can create a basic snackbar in Flutter:

void showSnackbar(BuildContext context, String message) {
  Scaffold.of(context).showSnackBar(
    SnackBar(
      content: Text(message),
    ),
  );
}

In this code, we import the Material library and then create a function named showSnackbar that takes in a BuildContext and a String message as its parameters. In the function body, we use the Scaffold.of method to access the nearest scaffold and call the showSnackBar method on it. We pass in a SnackBar widget that contains a Text widget with the message passed in as its content.

You can call this function anywhere in your Flutter code to show a snackbar with the given message.

The SnackBar widget also accepts a few optional properties, such as:

The SnackBar widget also accepts a few optional properties, such as:

  • duration: The amount of time the snackbar should be displayed on the screen before disappearing.
  • backgroundColor: The background color of the snackbar.
  • action: A button that the user can press to take an action related to the snackbar message.

Here’s an example of how to use these properties:

Scaffold.of(context).showSnackBar(
  SnackBar(
    duration: Duration(seconds: 2),
    backgroundColor: Colors.blue,
    content: Text(message),
    action: SnackBarAction(
      label: 'Undo',
      onPressed: () {
        // Do something when the user presses the undo button
      },
    ),
  ),
);

In this example, we set the duration to 2 seconds, the backgroundColor to blue, and include an action with a label of “Undo” and an onPressed callback that will be triggered when the user presses the undo button.

Snackbars are a great way to provide feedback to users in a non-intrusive manner. They are easy to implement and customize, making them a popular choice for many Flutter developers.

You can have in detail information on the SnackBar widget in this official Flutter Widget Of The Week from Google Flutter Team.