You are currently viewing Flutter SnackBar Tutorial and Example

Flutter SnackBar Tutorial and Example

  • Post author:
  • Post category:Toast

This is a Flutter Android SnackBar Tutorial and Example.

What is SnackBar?

SnackBar is a lightweight message with an optional action which briefly displays at the bottom of the screen.

SnakBars are important as they allows us show quick notifications for a short period of time without requiring user intervention.

However uses can also act by clicking the action button which can be rendered in the SnackBar.

Displaying a snackbar is easy. You simply invoke the Scaffold.of(context).showSnackBar(), passing an instance of SnackBar that describes the message.

You can also provide your own custom duration for displaying the SnackBar.

A SnackBar with an action will not time out when TalkBack or VoiceOver are enabled. This is controlled by AccessibilityFeatures.accessibleNavigation.

This is a simple Hello World App written in Flutter.

We make use of a button which when clicked renders our snackbar.

Both the button and snackbar are widgets.

Video Tutorial

We also have a video tutorial for this in our YouTube channel:

Common Classes You need to Know in this tutorial.

State - It is the State class where the logic behind a StatefulWidget is hosted.

StatelessWidget - A widget that does not require mutable state.

StatefulWidget - A widget that has mutable state.

Scaffold - Implements the basic material design visual layout structure.

This class provides APIs for showing drawers, snack bars, and bottom sheets.

SnackBar API Definition

SnackBar is a class that derives from the StatelessWidget class. The StatelessWidget is a class representing a widget that does not require mutable state. It's a widget as it itself derives from the Widget class.

Here's the class hierachy for the SnackBar:

Object -> Diagnosticable -> DiagnosticableTree -> Widget -> StatelessWidget -> SnackBar

Flutter SnackBar Example

Here's our snackbar example demo.

Flutter SnackBar

Flutter SnackBar

Let's start by explanations.

You import other packages or libraries to use into your flutter application using the import statement:

import 'package:flutter/material.dart';

In our caset we are importing the material.dart which will give our app a material design theme.

The entry point to dart applications like many languages is the main() function. In this case our main() function will be reponsible for instantiating our SnackBarDemo class.

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

We have two classes:

  1. SnackBarPage - To represent a single page in our application. This page will render our button which when clicked will display a snackbar.
  2. SnackBarDemo - To represent our full application.

Both the two classes are deriving from the StatelessWidget class. This implies that both won't have any mutable state.

In both classes we are overriding the build() method. The method should return us a Widget, however the widget is different in both cases.

The SnackBarPage should return us a Center widget. In Flutter almost all components are widgets. Even a class like Center which you would guess should only be aligning its children is a widget, albeit a StatelessWidget.

The Center widget will in this case have two children:

  1. a RaisedButton -this is the button that will be clicked.
  2. a Text - which will render some text.

At the end of the day we build that widget and return it. It will represent a single page.

The SnackBarDemo on the other hand will have it's build method building a widget representing the while app, a MaterialApp.

The MaterialApp will have the following parts;

  1. Title - Title of the app to be shown alongside the launcher icon
  2. AppBar - To represent the Toolbar. It will a Text widget to represent the title shown in toolbar.
  3. body - where we assign our SnackBarPage as the body of our app.
(a) pubspec.yaml

This is where we normally add our dependencies in flutter:

name: hello_flutter
description: Our Hello World Flutter Application.
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2
dev_dependencies:
  flutter_test:
    sdk: flutter
flutter:
  uses-material-design: true

You can find more info about pubspec here.

(b). main.dart

Here's our main.dart file.

import 'package:flutter/material.dart';
void main() => runApp(SnackBarDemo());
class SnackBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter SnackBar',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Simple Flutter SnackBar'),
        ),
        body: SnackBarPage(),
      ),
    );
  }
}
class SnackBarPage extends StatelessWidget {
  /**
  Comstruct our widget and return it.
   */
  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        onPressed: () {
          final snackBar = SnackBar(
            content: Text('How is the going?'),
            action: SnackBarAction(
              label: 'Undo',
              onPressed: () {
                // do something
              },
            ),
          );
          // Find the Scaffold in the Widget tree and use it to show a SnackBar!
          Scaffold.of(context).showSnackBar(snackBar);
        },
        child: Text('Show SnackBar'),
      ),
    );
  }
}
//end

How to Run.

  1. Create a Flutter Project, preferably in Android Studio.
  2. Copy the code above(main.dart) into yourmain.dart file under the libs directory.
  3. If you have an emulator or device running then click the run button.
  4. Or you can go over to the project folder in your explorer and build the project using the gradlew then drag the APK into your emulator or APK.