Flutter SnackBar Example

SnackBar is a lightweight message widget to show a at the bottom of your app screen. It can also contain an optional action also. In Flutter mobile Application  SnackBar is usually used with Scaffold and the usage is shown in the example below.

Flutter SnackBar Example –

In this flutter tutorial, we make an example with two buttons. When clicked on button  it calls a function that shows SnackBar message at the bottom of the screen. Lest Start on the topic Firstly you can create an flutter project. After create successfully your project open your main.dart file and used below code.

Main.dart File code .

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<MyApp> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  void _showScaffold(String message) {
    _scaffoldKey.currentState.showSnackBar(SnackBar(
      content: Text(message),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text('Flutter tutorial - codeplayon.com'),
        ),
        body: Center(
            child: Column(children: <Widget>[
              RaisedButton(
                textColor: Colors.white,
                color: Colors.green,
                child: Text('Welocme'),
                onPressed: () {
                  _showScaffold("Welcome to SnackBar.");
                },
              ),
              RaisedButton(
                textColor: Colors.white,
                color: Colors.deepPurpleAccent,
                child: Text('Walcome Flutter'),
                onPressed: () {
                  _showScaffold("This is a SnackBar in flutter.");
                },
              ),
            ])));
  }
}

After add these code you can run you flutter project When you run this Flutter application, you will get UI as shown up with two buttons.

 

How to show snackBar without Scaffold

It can get the current context and show snackbar like this:

void _showToast(BuildContext context) {
  final scaffold = Scaffold.of(context);
  scaffold.showSnackBar(
    SnackBar(
      content: const Text('Updating..'),
    ),
  );
}

this._showToast(context);

 

You may also like...