Scaffold.of() called with a context that does not contain a Scaffold
This exception happens because you are using the context
of the widget that instantiated Scaffold
. Not the context
of a child of Scaffold
.
You can solve this by just using a different context :
Scaffold( appBar: AppBar( title: Text('SnackBar Playground'), ), body: Builder( builder: (context) => Center( child: RaisedButton( color: Colors.pink, textColor: Colors.white, onPressed: () => _displaySnackBar(context), child: Text('Display SnackBar'), ), ), ),);
Note that while we're using Builder
here, this is not the only way to obtain a different BuildContext
.
It is also possible to extract the subtree into a different Widget
(usually using extract widget
refactor)
You can use a GlobalKey
. The only downside is that using GlobalKey might not be the most efficient way of doing this.
A good thing about this is that you can also pass this key to other custom widgets class that do not contain any scaffold. See(here)
class HomePage extends StatelessWidget { final _scaffoldKey = GlobalKey<ScaffoldState>(); \\ new line @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, \\ new line appBar: AppBar( title: Text('SnackBar Playground'), ), body: Center( child: RaisedButton( color: Colors.pink, textColor: Colors.white, onPressed: _displaySnackBar(context), child: Text('Display SnackBar'), ), ), ); } _displaySnackBar(BuildContext context) { final snackBar = SnackBar(content: Text('Are you talkin\' to me?')); _scaffoldKey.currentState.showSnackBar(snackBar); \\ edited line }}
You can solve this problem in two ways:
1) Using Builder widget
Scaffold( appBar: AppBar( title: Text('My Profile'), ), body: Builder( builder: (ctx) => RaisedButton( textColor: Colors.red, child: Text('Submit'), onPressed: () { Scaffold.of(ctx).showSnackBar(SnackBar(content: Text('Profile Save'),),); } ), ),);
2) Using GlobalKey
class HomePage extends StatelessWidget { final globalKey = GlobalKey<ScaffoldState>(); @override Widget build(BuildContext context) { return Scaffold( key: globalKey, appBar: AppBar( title: Text('My Profile'), ), body: RaisedButton( textColor: Colors.red, child: Text('Submit'), onPressed: (){ final snackBar = SnackBar(content: Text('Profile saved')); globalKey.currentState.showSnackBar(snackBar); }, ), ); }}