Flutter showSnackBar called on null

If you are inside a widget that does not has directly the return Scaffold(...) widget, you can do this:

Scaffold.of(context).showSnackBar(
 SnackBar(content: Text("Hello from snackbar",
 textAlign: TextAlign.center, style: TextStyle(fontSize: 14.0, fontWeight: 
 FontWeight.bold),), duration: Duration(seconds: 3), backgroundColor: Colors.blue,)
);

There is no need to create an extra Scaffold widget because the showSnackBar() method requires one, you can reuse.


You need to pass Key to Scaffold Widget also.

Then you can call -scaffoldKey.currentState.showSnackBar

@override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      .....

Tags:

Flutter