SnackBar In Flutter

Introduction

 
In this article, we will learn how to implement SnackBar in Flutter. Snackbar only works with Scaffold widget context. SnackBar is useful to show some task notification and get confirmation from the user for that. Let’s say you have removed some record from the app and showed confirmation to the user in the toast message box, but a user can not undo this operation. In this case, snackbar is very important as it provides an action so the user can undo it. We will take the same example to understand snackbar in Flutter application.
 
Output
 
 

Steps

 
Step 1
 
The first and most basic step is to create a new application in Flutter. If you are a beginner in Flutter, then you can check my blog Create a first app in Flutter. I have created an app named as “flutter_snackbar”.

Step 2
 
Now, create a listview using listview builder. We have generated temporary list using generate() method. Following is the code of it.
  1. var records = List<String>.generate(20, (index) => "Record : $index");   
Step 3
 
We will generate the listview and each item has a delete button which will delete the item and show snackbar at the bottom. Following is the implementation of that.
  1. Widget build(BuildContext context) {  
  2.  return Scaffold(  
  3.    appBar: AppBar(  
  4.      title: Text('SnackBar in Flutter'),  
  5.    ),  
  6.    body: ListView.builder(  
  7.      itemCount: records.length,  
  8.      itemBuilder: (context, index) {  
  9.        return ListTile(  
  10.          title: Text(records[index]),  
  11.          trailing: Container(  
  12.            width: 40,  
  13.            child: FlatButton(  
  14.              child: Icon(  
  15.                Icons.delete,  
  16.                color: Colors.purple,  
  17.              ),  
  18.              onPressed: () {  
  19.                showSnackBar(context, index);  
  20.              },  
  21.            ),  
  22.          ),  
  23.        );  
  24.      },  
  25.    ),  
  26.  );  
Step 4
 
Now, we will create a method, showSnackBar, which will show a snackbar at the bottom. We will implement action in snackbar to undo delete operation as well. Following is the programming implementation of that.
  1. void showSnackBar(BuildContext context, int index) {  
  2.    var deletedRecord = records[index];  
  3.    setState(() {  
  4.      records.removeAt(index);  
  5.    });  
  6.    SnackBar snackBar = SnackBar(  
  7.      content: Text('Deleted $deletedRecord'),  
  8.      action: SnackBarAction(  
  9.        label: "UNDO",  
  10.        onPressed: () {  
  11.          // print('Undo Delete of $message');  
  12.          setState(() {  
  13.            records.insert(index, deletedRecord);  
  14.          });  
  15.        },  
  16.      ),  
  17.    );  
  18.    Scaffold.of(context).showSnackBar(snackBar);  
  19.  }  
Step 5
 
Following is the full code of the example.
  1. import 'package:flutter/material.dart';  
  2. void main() => runApp(MyApp());  
  3. class MyApp extends StatelessWidget {  
  4.  @override  
  5.  Widget build(BuildContext context) {  
  6.    return MaterialApp(  
  7.      theme: ThemeData(  
  8.        primarySwatch: Colors.purple,  
  9.      ),  
  10.      home: MyHomePage(),  
  11.    );  
  12.  }  
  13. }  
  14.    
  15. class MyHomePage extends StatefulWidget {  
  16.  @override  
  17.  _MyHomePageState createState() => _MyHomePageState();  
  18. }  
  19.    
  20. class _MyHomePageState extends State<MyHomePage> {  
  21.  var records = List<String>.generate(20, (index) => "Record : $index");  
  22.  @override  
  23.  Widget build(BuildContext context) {  
  24.    return Scaffold(  
  25.      appBar: AppBar(  
  26.        title: Text('SnackBar in Flutter'),  
  27.      ),  
  28.      body: ListView.builder(  
  29.        itemCount: records.length,  
  30.        itemBuilder: (context, index) {  
  31.          return ListTile(  
  32.            title: Text(records[index]),  
  33.            trailing: Container(  
  34.              width: 40,  
  35.              child: FlatButton(  
  36.                child: Icon(  
  37.                  Icons.delete,  
  38.                  color: Colors.purple,  
  39.                ),  
  40.                onPressed: () {  
  41.                  showSnackBar(context, index);  
  42.                },  
  43.              ),  
  44.            ),  
  45.          );  
  46.        },  
  47.      ),  
  48.    );  
  49.  }  
  50.    
  51.  void showSnackBar(BuildContext context, int index) {  
  52.    var deletedRecord = records[index];  
  53.    setState(() {  
  54.      records.removeAt(index);  
  55.    });  
  56.    SnackBar snackBar = SnackBar(  
  57.      content: Text('Deleted $deletedRecord'),  
  58.      action: SnackBarAction(  
  59.        label: "UNDO",  
  60.        onPressed: () {  
  61.          // print('Undo Delete of $message');  
  62.          setState(() {  
  63.            records.insert(index, deletedRecord);  
  64.          });  
  65.        },  
  66.      ),  
  67.    );  
  68.    Scaffold.of(context).showSnackBar(snackBar);  
  69.  }  
  70. }  
Hooray…. Run the app and Test It on emulator/simulator or device :)))
 

Conclusion

 
We have learned how to implement the snackbar in Flutter and provide the action of undo in the snackbar as well. You have seen such snackbar features in Gmail.


Similar Articles