Flutter – How to show SnackBar

In this post, we will learn how to show SnackBar in flutter through a simple demo.

import 'package:flutter/material.dart';

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

class ShowSnackBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Coflutter - SnackBar',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Coflutter - SnackBar'),
          backgroundColor: const Color(0xffae00f0),
        ),
        body: SnackBarScreen(),
        // The snackbar will not overlap important widgets
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {},
        ),
      ),
    );
  }
}

class SnackBarScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        onPressed: () {
          showSnackBar(context);
        },
        child: Text('Show SnackBar'),
      ),
    );
  }

  void showSnackBar(BuildContext context) {
    final snackBar = SnackBar(
      content: const Text('Hello, Coflutter!'),
      backgroundColor: const Color(0xffae00f0),
      behavior: SnackBarBehavior.floating,
      duration: const Duration(seconds: 2),
      action: SnackBarAction(
          label: 'Done',
          textColor: Colors.white,
          onPressed: () {
            print('Done pressed!');
          }),
    );

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


Result


Some notes:

  • To show snack bar, we need a Scaffold as its parent.
  • Snack bar will not overlap other important widgets (FloatingActionButton in our example).
  • The snack bar appears at the bottom of the screen (Until now, there is no option to show snack bar at the top of screen). We need to custom widget or use external packages (like flushbar) to show similar snack bar at the top of screen.
  • There are 2 behaviors:
SnackBarBehavior.fixed (default)

…………………………………………

SnackBarBehavior.floating

Tagged : / /
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x