How to handle Scaffold.of() called with a context that does not contain a Scaffold exception?

This Exception was cause by using the context of Scaffold widget instead of Child widget in the widget Tree.

We handle this exception by two ways

Option1) Using Builder widget

Scaffold(
    appBar: AppBar(
        title: Text('Builder Widget'),
    ),
    body: Builder(
        builder: (context) => 
            Center(
            child: RaisedButton(
            color: Colors.pink,
            textColor: Colors.white,
            onPressed: () {
 final snackBar = SnackBar(content: Text('Flutter SnackBar'));
  Scaffold.of(context).showSnackBar(snackBar);

},
            child: Text('Display SnackBar'),
            ),
        ),
    ),
);

 

Option1) By Using Scaffold key

GlobalKey<ScaffoldState>_scaffoldKey=GlobalKey();
Scaffold(
  key: _scaffoldKey,
  appBar: AppBar(
    title: Text('Builder Widget'),
  ),
  body:  Center(
    child: RaisedButton(
      color: Colors.pink,
      textColor: Colors.white,
      onPressed: () {
        final snackBar = SnackBar(content: Text('Flutter SnackBar'));
       
        _scaffoldKey.currentState.showSnackBar(snackBar);
      },
      child: Text('Display SnackBar'),
    ),
  ),
),