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();
@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'),
),
),
),
);
}