Flutter - Showing Snackbar Examples

This tutorial gives you examples of how to display a snackbar in Flutter, including how to customize the snackbar.

A snackbar is used to display a short message. It's usually displayed at the bottom of the screen. Sometimes it can also have a clickable action button. In Flutter, there is a widget called SnackBar that makes it easy for us to show snackbars. This tutorial gives you examples of how to display a snackbar in Flutter, including how to customize the visual of the snackbar, set the display duration, add an action button, and set the theme data to configure the default property values.

Showing SnackBar Examples

There are two steps for displaying a snackbar. First, you have to create a SnackBar which can be done by calling the following constructor.

  const SnackBar({
    Key key,
    @required this.content,
    this.backgroundColor,
    this.elevation,
    this.margin,
    this.padding,
    this.width,
    this.shape,
    this.behavior,
    this.action,
    this.duration = _snackBarDisplayDuration,
    this.animation,
    this.onVisible,
  })

The only required parameter is content which is the widget to be displayed inside the snackbar. In most cases, the widget is a Text widget, but you can also use other types of Flutter widget.

  final _snackBar = SnackBar(
    content: Text('Welcome to woolha.com')
  );

Output:

Flutter - SnackBar - Basic

 

The second step is displaying the snackbar. A snackbar is not always displayed on screen. It's usually triggered by certain events such as button click. To display a snackbar, use ScaffoldState's showSnackBar method.

  Scaffold.of(context).showSnackBar(_snackBar);

Therefore, you must place the snackbar inside a Scaffold widget. It also helps to prevent the snackbar from overlapping other widgets such as FloatingActionButton and BottomNavigationBar.

Setting Background Color

You can set the background color of the snackbar by passing backgroundColor property. If you don't pass the parameter, it will use backgroundColor of ThemeData.snackBarTheme. If that value is also not specified, it will use a dark variation of ColorScheme.surface in light themes or ColorScheme.onSurface in dark themes.

  SnackBar(
    content: Text('Welcome to woolha.com'),
    backgroundColor: Colors.teal,
  )

Output:

Flutter - SnackBar - Background Color

 

Setting Padding

To set the padding for the snackbar's content and action, you can pass padding parameter (EdgeInsetsGeometry). Without passing this parameter, the default padding depends on behavior and action. If the behavior is fixed, the start padding is 24. If the behavior is floating, the start padding is 16. The same amount of padding will be added to the end if there is no action.

  SnackBar(
    content: Text('Welcome to woolha.com'),
    padding: EdgeInsets.all(15.0),
  )

Output:

Flutter - SnackBar - Padding

 

Setting Shape

You can change the shape of the snacbar's Material by passing a BorderShape as shape parameter. Without that parameter, it will use shape of ThemeData.snackBarTheme. If the theme data doesn't have that value, it depends on the used SnackBarBehavior. If the behavior is fixed, the default shape is rectangular. If the behavior is floating, it uses a RoundedRectangleBorder with a radius of 4.0..

  SnackBar(
    content: Text('Welcome to woolha.com'),
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
  )

Output:

Flutter - SnackBar - Shape

 

Setting Behavior, Width, and Margin

You can define how the snackbar should appear within a Scaffold by setting the value of behavior whose type is SnackBarBehaviorSnackBarBehavior with two values: fixed and floating.

If the value of behavior is fixed, the snackbar is fixed at the bottom of the Scaffold. The presence of the snackbar causes other non-fixed widgets such as FloatingActionButton to be pushed above. There is an exception when the Scaffold has a BottomNavigationBar, the snackbar will be displayed above the BottomNavigationBar. If you don't pass this parameter, behavior of ThemeData.snackBarTheme is used. If that value is also null, it will use fixed behavior.

  SnackBar(
    content: Text('Welcome to woolha.com'),
    behavior: SnackBarBehavior.floating,
  )

Output:

Flutter - SnackBar - Behavior Floating

 

If you set the snackbar behavior to floating, you can also set the width of the snackbar.

  SnackBar(
    content: Text('Welcome to woolha.com'),
    behavior: SnackBarBehavior.floating,
    width: 300,
  )

Output:

Flutter - SnackBar - Width

 

Or you can set the margin.

  SnackBar(
    content: Text('Welcome to woolha.com'),
    behavior: SnackBarBehavior.floating,
    margin: EdgeInsets.all(30.0),
  )

Output:

Flutter - SnackBar - Margin

 

width and margin can only be set if the behavior is set to floating. But you cannot define both width and margin as setting both properties causes assertion error.

Setting Action

You can add a clickable button inside the snackbar along with the action when the button is clicked. To do so, you need to create a SnackBarAction and passing it as action in the constructor of SnackBar. Creating a SnackBarAction can be done by calling its constructor which has the following named parameters.

  • Key key: The widget's key, used to control if it should be replaced.
  • Color textColor: The text color.
  • Color disabledTextColor: The text color when disabled.
  • String label *: The label of the button.
  • VoidCallback onPressed *: The callback to be called when the button is pressed.

*: required

 

Clicking the action button will cause the snackbar to be dismissed. Here is the example of how to define a SnackBarAction.

  SnackBar(
    content: Text('Welcome to woolha.com'),
    duration: const Duration(seconds: 10),
    action: SnackBarAction(
      label:'Click',
      onPressed: () {
        print('Action is clicked');
      },
      textColor: Colors.white,
      disabledTextColor: Colors.grey,
    ),
  )

Output:

Flutter - SnackBar - Action

 

Setting Duration

By default, a snackbar is shown for 4 seconds. To change the how long the snackbar should be displayed, you can define a Duration as duration parameter.

  SnackBar(
    content: Text('Welcome to woolha.com'),
    duration: const Duration(seconds: 10),
  )

 

Adding On Visible Callback

You can pass a callback function that will be called every time the snackbar becomes visible.

  SnackBar(
    content: Text('Welcome to woolha.com'),
    onVisible: () {
      print('Snackbar is visible');
    }
  )

 

Setting Theme Data

The customizations in the previous examples only apply to a specific button. What if you want to add a default style for all snackbars in your application. The solution is creating a SnackBarThemeData and pass it as snackBarTheme in the constructor of ThemeData. The constructor of SnackBarThemeData has the following parameters.

  • Color backgroundColor: Default value for SnackBar.backgroundColor.
  • Color actionTextColor: Default value for SnackBarAction.textColor.
  • Color disabledActionTextColor: Default value for SnackBarAction.disabledActionTextColor.
  • TextStyle contentTextStyle: Default TextStyle for SnackBar.content.
  • double elevation: Default value for SnackBar.elevation.
  • ShapeBorder shape: Default value for SnackBar.shape.
  • SnackBarBehavior: Default value for SnackBar.behavior.

Below is the example of how to set ElevatedButtonThemeData.

  theme: ThemeData(
    snackBarTheme: SnackBarThemeData(
      backgroundColor: Colors.teal,
      actionTextColor: Colors.white,
      disabledActionTextColor: Colors.grey,
      contentTextStyle: TextStyle(fontSize: 16),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
      behavior: SnackBarBehavior.floating,
    )
  )

Output:

Flutter - SnackBar - Theme Data

 

Full Code

import 'package:flutter/material.dart';
  
  void main() => runApp(MyApp());
  
  class MyApp extends StatelessWidget {
  
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Woolha.com Flutter Tutorial',
        home: _SnackBarAppExample(),
        theme: ThemeData(
          snackBarTheme: SnackBarThemeData(
            backgroundColor: Colors.teal,
            actionTextColor: Colors.white,
            disabledActionTextColor: Colors.grey,
            contentTextStyle: TextStyle(fontSize: 16),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
            behavior: SnackBarBehavior.floating,
          )
        ),
      );
    }
  }
  
  class _SnackBarAppExample extends StatelessWidget {
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Woolha.com Flutter Tutorial'),
        ),
        body: _MySnackBar(),
      );
    }
  }
  
  class _MySnackBar extends StatelessWidget {
  
    @override
    Widget build(BuildContext context) {
      final _snackBar1 = SnackBar(
        content: Text('Welcome to woolha.com'),
      );
  
      final _snackBar2 = SnackBar(
        content: Text('Welcome to woolha.com'),
        duration: const Duration(seconds: 10),
        action: SnackBarAction(
          label:'Click',
          onPressed: () {
            print('Action is clicked');
          },
          textColor: Colors.white,
          disabledTextColor: Colors.grey,
        ),
          onVisible: () {
            print('Snackbar is visible');
          },
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))),
        behavior: SnackBarBehavior.floating,
        margin: EdgeInsets.all(30.0),
        padding: EdgeInsets.all(15.0),
      );
  
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              child: Text('Show SnackBar 1'),
              onPressed: () {
                Scaffold.of(context).showSnackBar(_snackBar1);
              },
            ),
            ElevatedButton(
              child: Text('Show SnackBar 2'),
              onPressed: () {
                Scaffold.of(context).showSnackBar(_snackBar2);
              },
            )
          ],
        )
      );
    }
  }

Output:

Flutter - SnackBar - Full Code

 

SnackBar Properties

  • Key key: The widget's key, used to control if it should be replaced.
  • Widget content *: The content of the snackbar.
  • Color backgroundColor: The background color of the snackbar.
  • double elevation: The z-coordinate of the snackbar which affects the size of the shadow.
  • EdgeInsetsGeometry margin: Empty space outside the snackbar.
  • EdgeInsetsGeometry padding: Padding to be applied to the snackbar's content and action.
  • double width: The width of the snackbar.
  • ShapeBorder shape: The shape of the snackbar's Material.
  • SnackBarBehavior behavior: Defines the behavior and the location of the snackbar.
  • SnackBarAction action: An action that the user can take by clicking a button inside the snackbar.
  • Duration duration: How long the snackbar is displayed. Defaults to 4 seconds.
  • Animation<double> animation: Defines the entrance and exit animations of the snackbar.
  • VoidCallback onVisible: A callback function called the snackbar becomes visible in a Scaffold for the first time.

*: required