Notes by Lesnitsky Subscribe

#flutter ยท 2020-05-17 02:40 PM Twitter Logo

How to access Scaffold of context in the same widget it was created

FlutterError (Scaffold.of() called with a context that does not contain a Scaffold.

You might have seen the error above if you tried to use Scaffold.of(context) inside of a widget which creates Scaffold

Example:

class ScaffoldExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Example'),
),
body: Center(
child: FlatButton(
child: Text('Hello'),
onPressed: () {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text("I'm SnackBar"),
),
);
},
),
),
);
}
}

After you press the button, you'll get the error above

So, how to fix it?

One way to fix it is to move the body to separate widget

The code above turns into this

class ScaffoldExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Example'),
),
body: ScaffoldExampleBody(),
);
}
}

class ScaffoldExampleBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
child: Text('Hello'),
onPressed: () {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text("I'm SnackBar"),
),
);
},
),
);
}
}

Alternatively, you can pass a key to the scaffold

class ScaffoldExample extends StatelessWidget {
final GlobalKey scaffoldKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey, ... ); } }

access the state of the Scaffold

final state = scaffoldKey.currentState as ScaffoldState;

and call the showSnackBar on state:

state.showSnackBar(
SnackBar(
content: Text("I'm SnackBar"),
),
);

That's it!