Show snackbar from scaffold inside onPressed callback on Floating Action Button

Add a Globalkey of the Scaffold state and use that to display snack bar as below,

GlobalKey<ScaffoldState> scaffoldState;

Scaffold {
key: scaffoldState,
....


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

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

Tags:

Flutter