How to properly display a Snackbar in Flutter?

前端 未结 2 1877
渐次进展
渐次进展 2021-01-12 05:48

I am trying to show a Snackbar on click of a floatingActionbutton. But when I click on the floatingactionbutton it\'s not showing anyt

2条回答
  •  醉话见心
    2021-01-12 06:08

    That happens because the BuildContext used has not a Scaffold ancestor thus, won't be able to find it to render a SnackBar since it's up to the Scaffold to display it.

    According to the of method documentation:

    When the Scaffold is actually created in the same build function, the context argument to the build function can't be used to find the Scaffold (since it's "above" the widget being returned). In such cases, the following technique with a Builder can be used to provide a new scope with a BuildContext that is "under" the Scaffold:

    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Demo')
        ),
        body: Builder(
          // Create an inner BuildContext so that the onPressed methods
          // can refer to the Scaffold with Scaffold.of().
          builder: (BuildContext context) {
            return Center(
              child: RaisedButton(
                child: Text('SHOW A SNACKBAR'),
                onPressed: () {
                  Scaffold.of(context).showSnackBar(SnackBar(
                    content: Text('Hello!'),
                  ));
                },
              ),
            );
          },
        ),
      );
    }
    

    Solution

    Wrapping your FloatingActionButton in a Builder widget will make it possible in a more elegant way than using a GlobalKey, which was already mentioned by the @Epizon answer.

提交回复
热议问题