Flutter how to display flash/toast messages

Flutter Jun 10, 2023

The SnackBar widget in Flutter is used to show flash messages or notifications to users. The SnackBar widget is lightweight, customizable, and an essential part of Flutter. In this post, we will explore the various options available for working with SnackBar widgets in Flutter. You will learn how to create and show SnackBar widgets and discover different ways to customize them to fit the needs of your application.

1. Setting Up the Project

To begin, let us create a basic Flutter application that will show a SnackBar message when a button is pressed. We will start by setting up the main.dart file with the following code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Snackbar Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Snackbar Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Show Snackbar'),
          onPressed: () => ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('This is a snackbar'),
            ),
          ),
        ),
      ),
    );
  }
}

In the code snippet above, we have a simple Flutter application with a MyApp widget representing the root of the application. Inside the MyApp widget, we define a MyHomePage widget as the home page of the application.

The MyHomePage widget is a stateless widget that displays a Scaffold with an AppBar and a centered ElevatedButton. When the button is pressed, it triggers the onPressed callback, which shows a SnackBar using the ScaffoldMessenger.of(context).showSnackBar() method.

flutter_standard_snackbar_message

As you can see, displaying a flash message in Flutter is simple and straightforward. However, the default message we currently have is quite plain.

2. Customizing the Snackbar

Now let us take a closer look at customizing the design of our SnackBar widget. We have various options available to personalize its appearance and make it more visually appealing.

1.‚ÄÉContent

To change the SnackBar message, modify the content property of the SnackBar widget. And while we are on it let us align the text to the center as well. After all, we are using a Text widget in the content. For example:

const SnackBar(
  content: Text(
    'This is the text that our message will display',
    textAlign: TextAlign.center,
  ),
),

flutter_snackbar_with_new_centered_content

As you can see the text is now changed, and centered aligned. Feel free to change the text to whatever you want.

Keep in mind that the content property of the SnackBar accepts a widget, so you are not limited to using a Text widget inside the content.

2. Duration

To control how long the SnackBar is displayed on the screen, adjust the duration property of the SnackBar widget. You can set it to a specific duration using a Duration object. For example, to display the SnackBar for 1 second:

const SnackBar(
  content: Text(
    'This is the text that our message will display',
    textAlign: TextAlign.center,
  ),
  duration: Duration(seconds: 1),
),

flutter_snackbar_message_with_1_second_duration

3. Action

To add an action button to the SnackBar, use the action property of the SnackBar widget. The action is represented by a SnackBarAction widget and allows users to perform a specific action when pressed. For example:

SnackBar(
  content: const Text('This is the text that our message will display'),
  duration: const Duration(seconds: 1),
  action: SnackBarAction(
    label: 'Action',
    onPressed: changeButtonText,
  ),
),

flutter_snackbar_message_with_action_button

For demonstration purposes I made the action change the button text. For this to work in our example you need to change more than just adding the function to the onPressed property of the SnackBarAction.

If you are interested in it see the code snippet below, if not feel free to skip to the next customization option:

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  String buttonText = 'Show Snackbar';

  void changeButtonText() => setState(() => buttonText = 'I got changed');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Snackbar Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text(buttonText),
          onPressed: () => ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content:
                  const Text('This is the text that our message will display'),
              duration: const Duration(seconds: 1),
              action: SnackBarAction(
                label: 'Action',
                onPressed: changeButtonText,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

The MyHomePage class was transformed from a StatelessWidget to a StatefulWidget to enable dynamic updates by managing its state. A new variable called buttonText was introduced in the _MyHomePageState class, serving as a string to store the button's displayed text.

The _MyHomePageState class now includes the changeButtonText() function, responsible for changing the buttonText value upon calling. The ElevatedButton's child widget now displays the buttonText variable.

4. Background Color

To change the background color of the SnackBar, modify the backgroundColor property of the SnackBar widget. You can set it to any Color value. For example, to use an orange background color:

const SnackBar(
  content: Text(
    'This is the text that our message will display',
    textAlign: TextAlign.center,
    style: TextStyle(color: Colors.white),
  ),
  duration: Duration(seconds: 1),
  backgroundColor: Colors.orange,
),

flutter_snackbar_message_with_orange_background_color

5. Behavior

To control the behavior of the SnackBar, adjust the behavior property of the SnackBar widget. It accepts a SnackBarBehavior enum value. For example, to make the SnackBar float above other content:

const SnackBar(
  content: Text(
    'This is the text that our message will display',
    textAlign: TextAlign.center,
    style: TextStyle(color: Colors.white),
  ),
  duration: Duration(seconds: 1),
  backgroundColor: Colors.orange,
  behavior: SnackBarBehavior.floating,
),

flutter_snackbar_message_with_floating_behavior

6. Shape

To customize the shape of the SnackBar, modify the shape property of the SnackBar widget. It takes a ShapeBorder value. For example, to give the SnackBar rounded corners:

SnackBar(
  content: const Text(
    'This is the text that our message will display',
    textAlign: TextAlign.center,
    style: TextStyle(color: Colors.white),
  ),
  duration: const Duration(seconds: 1),
  backgroundColor: Colors.orange,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(50.0),
  ),
),

flutter_snackbar_message_with_rounded_corners

7. Margin

To add a margin around the SnackBar, adjust the margin property of the SnackBar widget. It takes an EdgeInsets value. For example, to add the same margins on all sides:

const SnackBar(
  content: Text(
    'This is the text that our message will display',
    textAlign: TextAlign.center,
    style: TextStyle(color: Colors.white),
  ),
  duration: Duration(seconds: 1),
  backgroundColor: Colors.orange,
  behavior: SnackBarBehavior.floating,
  margin: EdgeInsets.all(40),
),

To avoid errors when using the margin property the behavior property needs to be set to SnackBarBehavior.floating.

flutter_snackbar_message_with_margin_around

8. Padding

To add padding inside the SnackBar, adjust the padding property of the SnackBar widget. It takes an EdgeInsets value. For example, to add horizontal and vertical padding:

const SnackBar(
  content: Text(
    'This is the text that our message will display',
    textAlign: TextAlign.center,
    style: TextStyle(color: Colors.white),
  ),
  duration: Duration(seconds: 1),
  backgroundColor: Colors.orange,
  behavior: SnackBarBehavior.floating,
  padding: EdgeInsets.symmetric(vertical: 20, horizontal: 10),
),

flutter_snackbar_message_with_padding_inside

These are some of the most common options for customizing the SnackBar in Flutter. To learn more about these options and additional properties for further customization, you can refer to the SnackBar class in the Flutter documentation.

Displaying flash messages on top

In this post, we have been showing flash messages at the bottom of the screen. Sometimes, you might want to show these messages at the top of the screen instead. There are different ways to do this, and I have explained all of them in my other post:

Show SnackBar messages on top of the Screen in Flutter
The SnackBar widget in Flutter is a convenient way to display flash messages at the bottom of the screen. However, what if you want to show these messages at the top? In this post, I will show you how to do it. I will also introduce a third-party package that simplifies the process even further.

One of these implementations will look like this:

Additional styling using packages

So far we have used the properties of the SnackBar widget to adjust the styling. There are also packages available that can you help achieve even more styling possibilities. One such package is the awesome_snackbar_content package, read more about it in this post:

How to Create Awesome SnackBar Notifications
SnackBar notifications are a popular way to display flash messages or alerts to users in Flutter applications. In this post, we will explore how to create awesome SnackBar notifications using a package.

One of the styling options looks as follows, and it is very easy to do:

3. Conclusion

In this post, we learned how to work with SnackBar widgets in Flutter. We explored different options such as customizing the content, duration, action, backgroundColor, behavior, shape, margin, and padding of the SnackBar.

The SnackBar widget is a powerful tool for displaying important messages to users. By using the available customization options, you can create SnackBar widgets that match the style and functionality of your Flutter application.

Tags