gpt4 book ai didi

flutter - 在 float 操作按钮上的 onPressed 回调中从脚手架显示 snackbar

转载 作者:IT老高 更新时间:2023-10-28 12:34:59 26 4
gpt4 key购买 nike

我正在打电话

Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Snack text"),
));

在脚手架的floatingActionButtononPressed内。

我收到此错误

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

的 onPressed 中调用它,同样的解决方案就不起作用

最佳答案

更新:第二个解决方案比这个解决方案更好。

您应该将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com