I want to display a simple SnackBar inside Flutter\'s stateful widget. My application creates new instance of MaterialApp with a stateful widget ca
ScaffoldState
is now deprecated. Use ScaffoldMessengerState
.There are generally two ways of showing the SnackBar
using ScaffoldMessenger
.
Direct way:
@override
Widget build(BuildContext context) {
return Scaffold(
body: RaisedButton(
onPressed: () {
var snackBar = SnackBar(content: Text('Hello World'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
child: Text('Show SnackBar'),
),
);
}
Using GlobalKey
.
final _globalKey = GlobalKey<ScaffoldMessengerState>();
@override
Widget build(BuildContext context) {
return ScaffoldMessenger(
key: _globalKey,
child: Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
var snackBar = SnackBar(content: Text('Hello World'));
_globalKey.currentState.showSnackBar(snackBar);
},
child: Text('Show SnackBar'),
),
),
),
);
}
**
**
All the above solutions are amazing but as it's deprecated now you should use it this way.
var snackBar = SnackBar(content: Text('Hello World'));
ScaffoldMessenger.of(_scaffoldKey.currentContext)
.showSnackBar(snackBar );
To initialise a Snackbar on initState() you can execute a function after the layout is built.
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Your message here..")));}