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,
),
),
),
),
)
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);
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With