我正在打电话
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Snack text"),
));
在脚手架的floatingActionButton
的onPressed
内。
我收到此错误
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
....
当您在正文中调用 Scaffold.of(context)
时,它会指向一个解决方案。
https://docs.flutter.io/flutter/material/Scaffold/of.html
但是如果你在 FloatingActionButton
最佳答案
更新:第二个解决方案比这个解决方案更好。
您应该将 floatingActionButton 小部件放在 Builder 小部件中。 以下代码应该可以工作:
@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;
});
}
},
)
],
),
),
);
关于flutter - 在 float 操作按钮上的 onPressed 回调中从脚手架显示 snackbar ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50403382/