28

I am trying to show snackbar in my app to notify User but without scaffold it shows me error. My current code is:

scaffoldKey.currentState?.showSnackBar(
    new SnackBar(
      backgroundColor: color ?? Colors.red,
      duration: Duration(milliseconds: milliseconds),
      content: Container(
        height: 50.0,
        child: Center(
          child: new Text(
            title,
            style: AppTheme.textStyle.lightText.copyWith(color: Colors.white),
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    ),
  )
Code Hunter
  • 10,075
  • 23
  • 72
  • 102

5 Answers5

68

If you have access to context, from laszlo's answer, just call

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

If you dont have context (eg: showing network request error), use this snippet based on answer from Miguel Ruvio

We are going to use the property scaffoldMessengerKey which allows us to show snackbars without needing context with just one GlobalKey. Also, no need to add 3rd party packages like Get.


First, create a globals.dart to store a GlobalKey

//globals.dart

import 'package:flutter/material.dart';

final GlobalKey<ScaffoldMessengerState> snackbarKey =
    GlobalKey<ScaffoldMessengerState>();

Second, add scaffoldMessengerKey property to MaterialApp

//main.dart

import 'globals.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test',
      scaffoldMessengerKey: snackbarKey, // <= this
      ...

Finally, refer to this Key anywhere to show a Snackbar

// anywhere

import 'globals.dart';

final SnackBar snackBar = SnackBar(content: Text("your snackbar message"));
snackbarKey.currentState?.showSnackBar(snackBar); 
Bugzilla
  • 1,856
  • 1
  • 10
  • 16
9

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);
Gene
  • 4,192
  • 5
  • 32
  • 56
Manas
  • 3,060
  • 4
  • 27
  • 55
6

No, It is not possible. Snackbar is part of Scaffold. It must have a Scaffold parent. Snackbar

Inside Scaffold parent, you can do like below

BuildContext con=context;
final snackBar = SnackBar(content: Text(message));
Scaffold.of(con).showSnackBar(snackBar);
4

Scaffold.of(context).showSnackBar() is deprecated. You should use ScaffoldMessenger now.

Example: ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Clicked!")));

Here are listed the benefits of the new approach.

laszlo
  • 494
  • 4
  • 18
3

Use https://pub.dev/packages/get

then you can simply call the Get.snackbar() to show the snackbar where you want it to be displayed.

Get.snackbar('Hi', 'i am a modern snackbar');

NOTE

You can use this package when you don't have the context too.

Abel Tilahun
  • 1,705
  • 1
  • 16
  • 25
saswat saubhagya
  • 123
  • 1
  • 10