show toast widget flutter code example

Example 1: how to create a toast in flutter

You can show material design snackbars using the following code:

Scaffold.of(context).showSnackBar(SnackBar(
      content: Text("New Notification"),
    ));
   
In some cases, this will throw an error and it can be resolved using a workaround:

//Declare a GlobalKey
GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

//Assing this key to the scaffold
Scaffold(
  key: _scaffoldKey,
  body: ...
)

//finally in the topmost code use this key in the following way
_scaffoldKey.showSnackBar(SnackBar(
      content: Text("New Notification"),
    ));

Example 2: toast in flutter

Scaffold.of(context).showSnackBar(SnackBar(
      content: Text("Sending Message"),
    ));

Tags:

Dart Example