Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
SnackBar
2.1.
Constructor
2.2.
Properties
3.
Creating a SnackBar
3.1.
Create a Scaffold
3.2.
Display a SnackBar
3.3.
Provide an optional action
4.
Frequently Asked Questions
4.1.
How do you create a SnackBar class in Flutter?
4.2.
How do I get rid of SnackBar Flutter?
4.3.
What is the difference between toast and snackbar?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Flutter Snackbar

Author Sanjana Yadav
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Every piece of code you write in Flutter will be contained within a widget. Every element on the Flutter application's screen is a widget. The viewpoint of the screen is totally dependent on the widgets used to design the application. In addition, the structure of an application's code is a tree of widgets. Snackbar is a flutter widget that allows you to display a dismissible pop-up message on your app.

Let us now understand the Snackbar in detail.

SnackBar

The SnackBar is a lightweight widget in Flutter that pops up a small message in your app to notify the user when anything happens. With a SnackBar, you may display a message at the bottom of your app for a few seconds.

The snack bar appears at the bottom of the screen by default and disappears once the given time has passed. We can also create a custom snack bar with specific activities that allow users to add or delete any action or picture. SnackBar requires a Scaffold instance; with a Scaffold instance, your SnackBar will appear immediately.

To use a snackbar, you must first import "package:flutter/material.dart."

Constructor

SnackBar({Key key, 
@required Widget content, 
Color backgroundColor, 
double elevation, 
EdgeInsetsGeometry margin, 
EdgeInsetsGeometry padding, 
double width, 
ShapeBorder shape, 
SnackBarBehavior behavior, 
SnackBarAction action, 
Duration duration: _snackBarDisplayDuration, 
Animation<double> animation, 
VoidCallback onVisible})

Properties

The Flutter snack bar has the following important properties:

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Creating a SnackBar

Create a Scaffold

A Snackbar is presented inside a scaffold widget, which is used to design your mobile app's full visible screen. It is responsible for the appbar, title, and other body attributes that make up the widget tree.

Scaffold(  
 appBar: AppBar(  
   title: Text(' Flutter SnackBar Example'),  
 ),  
 body: SnackBarPage(),  
);  

Display a SnackBar

Display a SnackBar after the Scaffold is in place. Create a SnackBar first, then use ScaffoldMessenger to show it.

final snackBar = SnackBar(content: Text(' HELLO!! THIS IS A SNACKBAR'));    
// Here, we use the scaffold widget to show a snack bar.  
Scaffold.of(context).showSnackBar(SnackBar);  

Provide an optional action

When the SnackBar appears, you might wish to provide the user a choice. For example, if a user deletes a message by accident, they may retrieve it via an optional action in the SnackBar.

Here's an example of how to give the SnackBar widget a new action:

final snackBar = SnackBar(  
 content: Text('HELLO!! THIS IS A SNACKBAR'),  
 action: SnackBarAction(  
   label: 'Undo',  
   onPressed: () {  
     // code to undo the change.  
   },  
 ),  
);  

 

Let's now look at the complete code for the preceding phases. Replace the following code in the main.dart file. This code includes a button, which when clicked by the user, displays the snack bar message. It also has options for undoing and redoing the modifications.

import 'package:flutter/material.dart';
void main() {
  runApp(SampleApp());
}

class SampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: new ThemeData(
        primaryColor: const Color(0xFF43a047),
        accentColor: const Color(0xFFffcc00),
        primaryColorBrightness: Brightness.light,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter SnackBar Example'),
        ),
        body: SnackBarPage(),
      ),
    );
  }
}

class SnackBarPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        child: Text(
          'Click to See SnackBar',
          style: TextStyle(fontSize: 30.0),
        ),
        textColor: Colors.white70,
        color: Colors.deepOrangeAccent,
        padding: EdgeInsets.all(10.0),
        splashColor: Colors.brown.shade400,
        onPressed: () {
          final snackBar = SnackBar(
            content: Text('HELLO!! THIS IS A SNACKBAR.'),
            duration: Duration(seconds: 5),
            action: SnackBarAction(
              label: 'Undo',
              onPressed: () {
                // Some code to undo the change.
              },
            ),
          );
          Scaffold.of(context).showSnackBar(snackBar);
        },
      ),
    );
  }
}

Output

When we execute this program, the UI of the screen will appear as seen in the image below.

When we click the "Click to See SnackBar" button, the message appears at the bottom of the screen. After the stated time has passed, this message will be automatically erased. Look at the image below:

Frequently Asked Questions

How do you create a SnackBar class in Flutter?

In flutter, we can create a snackbar by invoking its function Object() { [native code] }. The only attribute that is necessary to construct a snackbar is content. We usually utilize a Text widget for content since we need to show the viewer something. If we wish, we may utilize other widgets instead.

How do I get rid of SnackBar Flutter?

You may hide the current SnackBar before it expires by using ScaffoldMessenger.of(ctx). hideCurrentSnackBar();

What is the difference between toast and snackbar?

Snackbars include a single line of text that is directly connected to the action taken. There may be a text action, but there are no icons. Toasts are mostly used for system messages (android only). They appear at the bottom of the screen as well, but they cannot be swiped off.

Conclusion

In this article, we have extensively discussed the Flutter Snackbar. We learned what a snackbar is, its properties and how to create a SnackBar in Flutter. 

We hope that this blog has helped you enhance your knowledge of the flutter framework and if you would like to learn more about flutter, check out our articles at Flutter

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Previous article
Flutter Progress Bar- Linear and Circular
Next article
Hive Flutter
Live masterclass