Show snackbar from scaffold inside onPressed callback on Floating Action Button

前端 未结 3 1109
星月不相逢
星月不相逢 2021-02-13 14:05

I am trying to call

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

inside onPressed of fl

3条回答
  •  后悔当初
    2021-02-13 14:16

    UPDATE: The second solution is better than this solution.

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

提交回复
热议问题