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

我正在打电话

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/

相关文章:

dart - Flutter - 我正在寻找一种制作脉冲动画的方法

flutter - 如何将抽屉小部件放在右侧

android - flutter 意外退出

dart - Flutter 中带有调整下拉箭头图标的全宽 DropdownButton

database - 任何用于 Flutter 的持久性 NoSQL 数据存储?

flutter - 如何使用flutter存储登录信息?

firebase - 使用 Flutter 向 Cloud Firestore 添加对象

dart - Flutter:右溢出 200 像素

dart - flutter 位置固定等效

dart - 如何在 Flutter 中更改 TextFormField 输入文本颜色