一尘不染

在浮动操作按钮上的onPressed回调中显示支架中的小吃店

flutter

我正在尝试打电话

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

里面onPressedfloatingActionButton支架。

我得到这个错误

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

但是,如果您在onPressed of中调用它,则相同的解决方案将不起作用 FloatingActionButton


阅读 288

收藏
2020-08-13

共1个答案

一尘不染

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

您应该将floatingActionButton小部件放在构建器小部件中。下面的代码应该工作:

@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;
                  });
                }
              },
            )
          ],
        ),
      ),
    );
2020-08-13