Answers for "how to show snackbar in initState() in flutter"

7

flutter snackbar showing error

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"),
    ));
Posted by: Guest on May-14-2020
0

how to show snackbar in initState() in flutter

// We can simply use the WidgetBinding instance to add a callback after the build method is called.. that will show the
// snackbar after the initState is completed and build method is called.

void initState() {
 super.initState();
WidgetsBinding.instance
    .addPostFrameCallback((_) => _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Your message here..")));
}
Posted by: Guest on July-07-2021

Code answers related to "how to show snackbar in initState() in flutter"

Code answers related to "Dart"

Browse Popular Code Answers by Language