当前位置:  开发笔记 > 编程语言 > 正文

显示来自scaffold里面的snackbar on onPressed回调on Floating Action Button

如何解决《显示来自scaffold里面的snackbarononPressed回调onFloatingActionButton》经验,为你挑选了2个好方法。

我想打电话

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中调用它,同样的解决方案就不起作用了 FloatingActionButton



1> Antonino Cac..:

您应该将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: [
            new MySwitch(
              value: _switchValue,
              onChanged: (bool value) {
                if (value != _switchValue) {
                  setState(() {
                    _switchValue = value;
                  });
                }
              },
            )
          ],
        ),
      ),
    );



2> Vinoth Kumar..:

添加一个脚手架状态的全局键,并使用它来显示小吃店,如下所示,

GlobalKey scaffoldState;

Scaffold {
key: scaffoldState,
....


scaffoldState.currentState.showSnackBar(new SnackBar(content: new Text('Hello!')));

推荐阅读
echo7111436
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有