Flutter SnackBar Action

SnackBar is used to show a message to user for a brief period of time. Also, you can provide an action label in SnackBar to perform an action when pressed on it.

In this tutorial, we will learn how to provide an Action label in SnackBar.

Following is a quick syntax to provide an Action inside SnackBar.

SnackBar(
  content: Text(message),
  action: SnackBarAction(
    label: 'Undo', // or some operation you would like
    onPressed: () {
  	  // this block runs when label is pressed
    },
  ),
)

SnackBar has a property called action that accepts a SnackBarAction widget.

SnackBarAction has label which gets displayed like a secondary button with no background color or border. But when pressed, you can run some code using onPressed() property as shown in the above code snippet.

Example: SnackBar Action

In this example, we shall implement a SnackBar that shows a message. Also, we have an action which when pressed, prints something to the console. You may place code in place of this print statement as per your application requirement.

main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  void _showMessageInScaffold(String message){
    try {
      _scaffoldKey.currentState.showSnackBar(
          SnackBar(
            content: Text(message),
            action: SnackBarAction(
              label: 'Undo',
              onPressed: () {
                // some code
                print('Action in Snackbar has been pressed.');
              },
            ),
          )
      );
    } on Exception catch (e, s) {
      print(s);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text('Flutter Tutorial - googleflutter.com'),
        ),
        body: Center(
            child: RaisedButton(
              textColor: Colors.white,
              color: Colors.blue,
              child: Text('Show SnackBar'),
              onPressed: (){
                _showMessageInScaffold("Hello dear! I'm SnackBar.");
              },
            )
        )
    );
  }
}

Screenshot

Flutter SnackBar Action

Summary

In this Flutter Tutorial, we learned how to display an action in SnackBar, with the help of well detailed example Flutter Application.

Desclaimer: We are not affiliated, associated, authorized, endorsed by, or in any way officially connected with the Google, Apple or Flutter, or any of its subsidiaries or its affiliates. The names Google, Apple and Flutter as well as related names, marks, emblems and images are registered trademarks of their respective owners. This site googleflutter.com covers tutorials related to Flutter developed by Google.