I am trying to call
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Snack text"),
));
inside onPressed
of floatingActionButton
of scaffold.
I get this error
I/flutter (18613): Scaffold.of() called with a context that does not contain a Scaffold.
I/flutter (18613): No Scaffold ancestor could be found starting from the context that was passed to
....
And it points to a solution when you call Scaffold.of(context)
inside a body.
https://docs.flutter.io/flutter/material/Scaffold/of.html
But the same solution doesnt work if you call it inside onPressed of FloatingActionButton
The ElevatedButton is a child widget placed on the return Center . Then, we use the ScaffoldMessenger class to display the SnackBar. Clicking on the button will show the SnackBar with the following message: “Hi, I am a SnackBar!”
We already have a SnackBar widget on Flutter to show such errors or warning messages. To display it using ScaffoldMessenger . Inside the SnackBar, the content is a simple text. If you click on the show message button.
Old answer. ScaffoldMessenger shows SnackBar in the nearest descendant Scaffold . If you add another Scaffold before AlertDialog , it will use it instead of the root one which is left behind the dialog.
you probably have a parent widget that contains Scaffold as well. Create a scaffoldKey for that and pass it to your child widget that have to show the Snakcbar . Note that you can't use Sanckbar without Scaffold widget.
UPDATE: The second solution is better than this solution.
You should put the floatingActionButton widget in a Builder Widget. The following code should work:
@override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton: new Builder(builder: (BuildContext context) {
return new FloatingActionButton(onPressed: () {
Scaffold
.of(context)
.showSnackBar(new SnackBar(content: new Text('Hello!')));
});
}),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: new Column(
children: <Widget>[
new MySwitch(
value: _switchValue,
onChanged: (bool value) {
if (value != _switchValue) {
setState(() {
_switchValue = value;
});
}
},
)
],
),
),
);
Add a Globalkey of the Scaffold state and use that to display snack bar as below,
GlobalKey<ScaffoldState> scaffoldState;
Scaffold {
key: scaffoldState,
....
scaffoldState.currentState.showSnackBar(new SnackBar(content: new Text('Hello!')));
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