How to implement flash error messages in Flutter

Flash error messages are essential for providing immediate feedback to users when errors occur in our Flutter application. The SnackBar widget offers an effective way to display temporary messages that alert users about issues and guide them on how to proceed. This Answer will walk us through the steps to implement flash error messages using the SnackBar widget in our Flutter app.

Constructor and parameters

The SnackBar widget provides a constructor with various parameters to customize its behavior and layout.

const SnackBar({
  Key? key,
  required Widget content,
  Color? backgroundColor,
  double? elevation,
  EdgeInsetsGeometry? margin,
  EdgeInsetsGeometry? padding,
  double? width,
  ShapeBorder? shape,
  SnackBarBehavior? behavior,
  SnackBarAction? action,
  double? actionOverflowThreshold,
  bool? showCloseIcon,
  Color? closeIconColor,
  Duration duration = _snackBarDisplayDuration,
  Animation<double>? animation,
  VoidCallback? onVisible,
  DismissDirection dismissDirection = DismissDirection.down,
  Clip clipBehavior = Clip.hardEdge
})

Let's take a closer look at each parameter and its purpose.

  1. key: A unique identifier for the widget.

  2. content: Main content of the snack bar.

  3. backgroundColor: Background color of the snack bar.

  4. elevation: Elevation of the snack bar.

  5. margin: Outer margins around the snack bar.

  6. padding: Padding within the snack bar.

  7. width: Width of the snack bar.

  8. shape: Shape of the snack bar.

  9. behavior: Behavior when multiple snack bars are displayed.

  10. action: Action button within the snack bar.

  11. actionOverflowThreshold: Action button overflow threshold.

  12. showCloseIcon: Option to show a close icon.

  13. closeIconColor: Color of the close icon.

  14. duration: Duration for which the snack bar is displayed.

  15. animation: Animation for showing/hiding the snack bar.

  16. onVisible: Callback when the snack bar becomes visible.

  17. dismissDirection: Direction to dismiss the snack bar.

  18. clipBehavior: How the content should be clipped.

Import required packages

To use the SnackBar widget, we need to import the necessary packages in our Dart file.

import 'package:flutter/material.dart';

Create a function for flash errors

To simplify the process of showing flash error messages using the SnackBar, create a function that takes the error message and a BuildContext as parameters. This function will display the SnackBar:

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

Trigger flash error messages

Now that we have a function to display flash error messages using the SnackBar, we can call it to provide feedback to users when errors occur in our app. For example, we can call the showFlashError function inside a try-catch block:

try {
// Your code that might throw an error
} catch (e) {
showFlashError(context, 'An error occurred. Please try again.');
}

After running the above code, we can see the following output:

Customize the flash error messages

We can further customize the appearance of our flash error messages by adjusting the properties of the SnackBar widget. For instance, we can provide an action button for users to dismiss the message or to perform an action related to the error:

void showFlashError(BuildContext context, String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Container(
height: 30, // Adjust the height as needed
child: Row(
children: [
Icon(Icons.error, color: Colors.white),
SizedBox(width: 10),
Expanded(
child: Text(
message,
style: TextStyle(color: Colors.white),
overflow: TextOverflow.visible,
),
),
],
),
),
backgroundColor: Colors.blue,
duration: Duration(seconds: 3),
action: SnackBarAction(
label: 'Dismiss',
textColor: Colors.white,
backgroundColor: Colors.black,
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
),
);
}

Explanation

  • Lines 419: This block of code defines the content of the SnackBar. It uses a Container widget to wrap the content.

    • Line 5: This line specifies the height of the Container, adjusting the height to fit the content.

    • Line 6–18: A horizontal layout is established within a Container to arrange its children in a row, displaying a white error icon followed by a 10-unit spacing and an Expanded Text widget presenting the message in white using TextStyle.

  • Line 20: This line sets the background color of the SnackBar to blue.

  • Line 21: This line specifies that the SnackBar will be displayed for 3 seconds.

  • Lines 22–29: This block of lines defines an action button within the SnackBar.

    • Line 23: It sets the label text for the action button to “Dismiss.”

    • Line 24: It sets the text color of the action button’s label to white.

    • Line 25: It also sets the background color of the action button to black.

    • Lines 26–28: These lines define the action to be taken when the button is pressed. In this case, it hides the current SnackBar.

After running the above code, we can see the following output:

Code example

We get the following code by putting together the code explained above.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Educative SnackBar Answer',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
 void showFlashError(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Container(
          height: 30, // Adjust the height as needed
          child: Row(
            children: [
              Icon(Icons.error, color: Colors.white),
              SizedBox(width: 10),
              Expanded(
                child: Text(
                  message,
                  style: TextStyle(color: Colors.white),
                  overflow: TextOverflow.visible,
                ),
              ),
            ],
          ),
        ),
        backgroundColor: Colors.blue,
        duration: Duration(seconds: 3),
        action: SnackBarAction(
          label: 'Dismiss',
          textColor: Colors.white,
          backgroundColor: Colors.black,
          onPressed: () {
            ScaffoldMessenger.of(context).hideCurrentSnackBar();
          },
        ),
      ),
    );
  }

  void simulateError(BuildContext context) {
    try {
      // Simulating an error
      throw Exception('Simulated Error');
    } catch (e) {
      showFlashError(context, 'An error occurred!');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Educative SnackBar Answer'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            simulateError(context);
          },
          child: Text('Trigger Error'),
        ),
      ),
    );
  }
}

Conclusion

By implementing flash error messages using the SnackBar widget, we can enhance the user experience of our Flutter app by providing immediate and contextually relevant feedback. Utilizing the SnackBar widget's flexibility, we can create a user-friendly error-handling system that guides users through unexpected scenarios.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved