在浮动操作按钮上的onPressed回调中显示支架中的小吃店 [英] Show snackbar from scaffold inside onPressed callback on Floating Action Button

查看:107
本文介绍了在浮动操作按钮上的onPressed回调中显示支架中的小吃店的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试致电

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)时,它指向一种解决方案.

And it points to a solution when you call Scaffold.of(context) inside a body.

https://docs.flutter.io/flutter/material/Scaffold/of.html

但是,如果您在FloatingActionButton

推荐答案

更新:第二种解决方案比该解决方案好.

UPDATE: The second solution is better than this solution.

您应该将floatActionButton窗口小部件放置在Builder窗口小部件中. 以下代码应该可以工作:

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;
                  });
                }
              },
            )
          ],
        ),
      ),
    );

这篇关于在浮动操作按钮上的onPressed回调中显示支架中的小吃店的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆