8. Flutter Tutorial for Beginners – Flutter Snackbar

0
749

Step 1. Open your flutter project.

Step 2. Declare a Global key into the class which contain the Scaffold widget.

final GlobalKey _scaffoldKey = new GlobalKey();

Step 3. Define the Scafold key.

Scaffold(
  key: _scaffoldKey,
  appBar: AppBar(
    title: Text('First Page'),
  ),

Step 4. Write down the following code for snackbar.

_scaffoldKey.currentState.showSnackBar(
    SnackBar(
      content: Text('This is your snackbar!!!'),
      duration: Duration(seconds: 3),

    ));

If you want to create a onPressed() event for snackbar follow the given code

_scaffoldKey.currentState.showSnackBar(
    SnackBar(
      content: Text('This is your snackbar!!!'),
      duration: Duration(seconds: 3),
      action: SnackBarAction(
        label: 'Undo',
        onPressed: (){
          //here you code
        },
      ),

    ));

Full Example:

import 'package:flutter/material.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  final GlobalKey _scaffoldKey = new GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Show Snackbar'),
          onPressed: (){
            _scaffoldKey.currentState.showSnackBar(
                SnackBar(
                  content: Text('This is your snackbar!!!'),
                  duration: Duration(seconds: 3),
                  action: SnackBarAction(
                    label: 'Undo',
                    onPressed: (){
                      //here you code
                    },
                  ),

                ));
          },
        ),
      ),
    );
  }

}

LEAVE A REPLY

Please enter your comment!
Please enter your name here