how to show snackbar in flutter

Hi Guys, Welcome to Proto Codes Point, In this flutter tutorial we check how to show snackbar in flutter app development.

What is Snackbar?

A Flutter Snackbar is Quick Information to the user of your application. Using material design snackbar you can give a quick message, error or warning message to the app user,

One of the best and the most useful way of showing message or notification is by using Flutter Material Snackbar.

Video Tutorial 

ScaffordMessenger – scaffold.of(context) error solution

How to Show Snackbar?

Step 1: Create a new Project

Of course, you need to create a new Flutter project in Android Studio or VSCode whichever is your favourite IDE.

Step2: Initialise a global key scaffold

Create a stateful class and declare a Global key scaffold state

final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();

Step 3: Create a method of Snackbar bar

void _showSnackbar() {
   final snack = SnackBar(
     content: Text("This is Snackbar Example"),
     duration: Duration(seconds: 15),
     backgroundColor: Colors.green,
   );

   _globalKey.currentState.showSnackBar(snack);
  }

Step 4: Call the method to show snackbar

Then, ok to call the method _showSnackbar we will make use of the RaisedButton widget in a flutter, when it is been pressed the method is been called and this method will showSnackBar using scaffordState globalkey.

RaisedButton(
              onPressed: () {
                _showSnackbar();  // calling the method on pressed
              },
              child: Text("Click me"),
            
),

1st. Way using _globalKey.currentState – Show Snackbar in flutter App

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Snackbar(),
    );
  }
}

class Snackbar extends StatefulWidget {
  @override
  _SnackbarState createState() => _SnackbarState();
}

class _SnackbarState extends State<Snackbar> {

  final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey,
      appBar: AppBar(title: Text("Flutter Snackbar Example"),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("press to show Snackbar"),
            RaisedButton(
              onPressed: () {
                _showSnackbar();
              },
              child: Text("Click me"),
            )
          ],
        ),
      ),
    );
  }

  void _showSnackbar() {
   final snack = SnackBar(
     content: Text("This is Snackbar Example"),
     duration: Duration(seconds: 15),
     backgroundColor: Colors.green,
   );

   _globalKey.currentState.showSnackBar(snack);
  }
}







2nd. Way using ScaffoldMessenger.of(context).showSnackBar

Show Snackbar in flutter using ScaffoldMessenger.of(context).shotSnackbar(snackbar);

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SnackBarExample(),
    );
  }
}

class SnackBarExample extends StatefulWidget {
  @override
  _SnackBarExampleState createState() => _SnackBarExampleState();
}

class _SnackBarExampleState extends State<SnackBarExample> {

  //creating an instance of Snackbar to use it in scaffoldMessenger
  final snackBar = SnackBar(content: Text('New Way to show snackbar'),duration: Duration(seconds:1 ),action: SnackBarAction(
    onPressed: (){

    }, label: 'Button',
  ),);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            EButton(),
            ElevatedButton(onPressed: (){
            // using ScaffoldMessenger
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            }, child: Text('New Snackbar')),
          ],
        ),
      ),
    );
  }
}

Conclusion

Yes, Flutter provides its own Snackbar, but the only drawable of default is it create lots of boilerplate code and is not as customizable, so making use of the Flutter Flushbar library will remove this drawable and you can easily style as per your creativity that too without any scaffold.

This library is useful when you want to show more than a simple message.