在浮动动作按钮上显示来自脚手架里面的快餐栏onPressed回调

时间:2018-05-18 03:32:54

标签: flutter

我正打算致电

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

onPressed脚手架的floatingActionButton内。

我收到此错误

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中调用它,那么同样的解决方案也无效

3 个答案:

答案 0 :(得分:7)

您应该将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;
                  });
                }
              },
            )
          ],
        ),
      ),
    );

答案 1 :(得分:5)

添加Scaffold状态的Globalkey并使用它 显示小吃店如下,

GlobalKey<ScaffoldState> scaffoldState;

Scaffold {
key: scaffoldState,
....


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

答案 2 :(得分:2)

这甚至更简单。 尝试过。将FloatingActionButton创建为单独的无状态小部件。 从支架中调用此无状态小部件。

class Abc extends StatelessWidget
{
   Widget build(BuildContext context)
   {
      return Scaffold(
         appBar:AppBar(title:Text("Long List View")),
         body:SomeOtherWidget(),
         floatingActionButton:MyFAB()  
      );
   }
}

class MyFAB extends StatelessWidget
{
    Widget build(BuildContext context)
    {
       return FloatingActionButton(
            onPressed:(){
                showSnackBarHandler(context);
            },
            child:Icon(Icons.add),
            tooltip:"Press to Add More"
       );
    }
}

void showSnackBarHandler(BuildContext context){

var snackBar = SnackBar(
    content:Text("Hello")
);

Scaffold.of(context).showSnackBar(snackBar);

}