Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show snackBar without Scaffold

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,
          ),
        ),
      ),
    ),
  )
like image 681
Code Hunter Avatar asked Jul 30 '19 08:07

Code Hunter


3 Answers

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); 
like image 143
Bugzilla Avatar answered Oct 23 '22 23:10

Bugzilla


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);
like image 11
Manas Avatar answered Oct 23 '22 21:10

Manas


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);
like image 5
Manikandan Selvanathan Avatar answered Oct 23 '22 21:10

Manikandan Selvanathan