How to Create flash messages using MaterialBanner

Flutter Jun 18, 2023

Flash messages are an essential component of any user interface that allows you to display brief, informative messages to users. In Flutter, the MaterialBanner widget provides a convenient way to create and display flash messages on top of the screen within your application. In this post, we will explore how to create, dismiss, and style the MaterialBanner widget.

Setting up

Before we dive into creating flash messages, let us set up a basic Flutter project in our main.dart file. Here is the initial code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Material Banner Example',
      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('Material Banner Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {},
          child: const Text('SHOW BANNER'),
        ),
      ),
    );
  }
}

In this code snippet, we have a MaterialApp that will display our MyHomePage widget. Within the MyHomePage widget, we have a Scaffold that contains an AppBar and an ElevatedButton widget. When the button is pressed, we want to show the MaterialBanner widget.

flutter_displaying_elevated_button

To prevent encountering the "No ScaffoldMessenger widget found" error, we have placed the Scaffold in a separate widget, allowing access to the MaterialApp's context. If you're curious, you can find more information about this error in the following post.

No ScaffoldMessenger widget found
When using the ScaffoldMessenger widget in Flutter, you may encounter the puzzling “No ScaffoldMessenger widget found” error. In this post, we will explore this common error message and go over different solutions to resolve it.

1. Displaying the MaterialBanner

Now that we have our project set up, let us move on to displaying the MaterialBanner widget. We will update the MyHomePage widget by replacing the onPressed callback of the ElevatedButton with code that shows the MaterialBanner when pressed. Here is the modified code snippet:

body: Center(
  child: ElevatedButton(
    onPressed: () => ScaffoldMessenger.of(context).showMaterialBanner(
      const MaterialBanner(
        content: Text('This is a material banner.'),
        actions: [
          SizedBox(),
        ],
      ),
    ),
    child: const Text('SHOW BANNER'),
  ),
),

We are using the ScaffoldMessenger.of(context).showMaterialBanner() function to show a MaterialBanner. As you can see, the function takes a MaterialBanner widget as an argument. Inside the MaterialBanner, we set the content of our message using the content property. We also set the actions property because this one is required as well. Currently, the actions property has a SizedBox() widget as a placeholder to avoid errors.

flutter_displaying_default_material_banner

2. Dismissing the MaterialBanner

The MaterialBanner widget can only be manually dismissed, meaning it will not disappear automatically after a certain duration, and there is no duration property available. To allow users to dismiss the banner, we add a dismiss action button to the MaterialBanner.

body: Center(
  child: ElevatedButton(
    onPressed: () => ScaffoldMessenger.of(context).showMaterialBanner(
      MaterialBanner(
        content: const Text('This is a material banner.'),
        actions: [
          OutlinedButton(
            onPressed: () =>
                ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
            child: const Text('DISMISS'),
          ),
        ],
      ),
    ),
    child: const Text('SHOW BANNER'),
  ),
),

In the code snippet, we added an OutlinedButton as the action within the actions property of the MaterialBanner. Pressing the button will hide the current MaterialBanner using the ScaffoldMessenger.of(context).hideCurrentMaterialBanner() function.

flutter_displaying_default_material_banner_with_dismiss_button

3. Styling the MaterialBanner

To make the flash messages visually appealing, we can customize the appearance of the MaterialBanner widget. This includes changing the background color, modifying the text styles, and adding icons. See the following code snippet:

body: Center(
  child: ElevatedButton(
    onPressed: () => ScaffoldMessenger.of(context).showMaterialBanner(
      MaterialBanner(
        leading: const Icon(
          Icons.check,
          color: Colors.white,
        ),
        content: const Text(
          'This is a material banner.',
        ),
        contentTextStyle: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
        backgroundColor: Colors.green,
        elevation: 1,
        actions: [
          OutlinedButton(
            style: OutlinedButton.styleFrom(
              foregroundColor: Colors.white,
              side: const BorderSide(color: Colors.white),
            ),
            onPressed: () =>
                ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
            child: const Text(
              'DISMISS',
            ),
          ),
        ],
      ),
    ),
    child: const Text('SHOW BANNER'),
  ),
),

In the code snippet, we made the following changes:

First, we added an Icon widget to the leading property. By setting the Icons.check and specifying the color as Colors.white, we included an icon at the left side of the MaterialBanner.

Next, we modified the text style of the content by setting the contentTextStyle property. By using TextStyle, we adjusted the color property to Colors.white and set the fontWeight to FontWeight.bold.

To change the background color of the MaterialBanner, we set the backgroundColor property to Colors.green.

We also set the elevation property to 1 to ensure that the widgets below the MaterialBanner do not get pushed down, providing a better user experience.

For the dismiss action button, we customized the OutlinedButton using OutlinedButton.styleFrom(). Within the styleFrom() method, we set the foregroundColor to Colors.white and specified a white border using side with a BorderSide object.

flutter_displaying_styled_material_banner

4. Style the MaterialBanner using a package

If the customization options of the MaterialBanner widget are not sufficient for your requirements or if you prefer a more convenient way to style them. You can consider using the awesome_snackbar_content package. This package comes with predefined styles to style both the content of the SnackBar and MaterialBanner widgets.

flutter_displaying_styled_material_banner_using_awesome_snackbar_content

See my other post for clear instructions on how to implement it:

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.

Conclusion

In this post, we covered the process of creating flash messages using Flutter's MaterialBanner widget. We set up a basic Flutter project, to display the MaterialBanner with customized content, an action button, and enabled the dismissal functionality. We also explored styling options to enhance the visual appeal of the flash messages using MaterialBanner.

Tags