How to Show SnackBar in Flutter

In Material Design, a SnackBar shows the user briefly with some kind of useful information. Having SnackBar in your mobile application will really help users to get information about their actions inside the app. In this blog post, let’s see how to add and show SnackBar in Flutter.

SnackBar class is needed to create a snack bar widget in Flutter. You can create a simple snack bar as given in the snippet below:

final snackBar = SnackBar(
            content: Text('Hello! I am a SnackBar!'),
            duration: Duration(seconds: 5),
            action: SnackBarAction(
              label: 'Undo',
              onPressed: () {
                // Some code to undo the change.
              },
            ),
          );

As you see, the properties of the SnackBar class are really understandable. You can define content, duration, and action of snack bar easily.

You can show the SnackBar using the snippet given below:

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

Following is the complete Flutter tutorial to show SnackBar. While Pressing the RaisedButton the snack bar appears for the given duration.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter snackbar example'),
        ),
        body: Center(child: Body()),
      ),
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.center,
      child: RaisedButton(
        onPressed: () {
          final snackBar = SnackBar(
            content: Text('Hello! I am a SnackBar!'),
            duration: Duration(seconds: 5),
            action: SnackBarAction(
              label: 'Undo',
              onPressed: () {
                // Some code to undo the change.
              },
            ),
          );

          // Find the Scaffold in the widget tree and use
          // it to show a SnackBar.
          Scaffold.of(context).showSnackBar(snackBar);
        },
        child: const Text('Click Me!', style: TextStyle(fontSize: 20)),
        color: Colors.blue,
        textColor: Colors.white,
        elevation: 5,
      ),
    );
  }
}

Following is the output of Flutter SnackBar example:

flutter snackbar example

Leave a Comment

Your email address will not be published. Required fields are marked *