I am trying to learn more about BuildContext
and Scaffold.of()
.
I understand that when you are displaying a SnackBar
you often need to add a Builder
to get the context 'under' the Scaffold you have added.
As such:
class MyScreen extends StatelessWidget {
build(BuildContext context) {
return Scaffold(
body: Builder(
builder: (context) =>
RaisedButton(
child: Text('push me'),
onPressed: () => Scaffold.of(context).showSnackBar(
SnackBar(content: Text('this will work'))),
),
));
}
}
My question is this: If Scaffold.of()
gets the closest ancestor, shouldn't it usually eventually find something higher up the widget tree, eg the SplashScreen scaffold? When we take away the builder and create this incorrect code:
class MyScreen extends StatelessWidget {
build(BuildContext context) {
return Scaffold(
body: RaisedButton(
child: Text('push me'),
onPressed: () => Scaffold.of(context).showSnackBar(
SnackBar(content: Text('broken'))),
),
));
}
}
then we get the standard error Scaffold.of() called with a context that does not contain a Scaffold. I/flutter ( 7750)
Scaffold.of() called with a context that does not contain a Scaffold. I/flutter ( 7750)
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of().
Even though there is no direct parent Scaffold in the BuildContext
, how can no Scaffold ancestor be found at all (for example a Grandparent ancestor)? All the previous pages in my application had a scaffold, are they no longer in the widget tree?
I understand that if it found a Scaffold and rendered the SnackBar that we wouldn't be able to see it, but I still don't understand how it doesn't find one. Perhaps I've misunderstood what 'ancestor' means.
Thank you
BuildContext
represents the location of one specific widget in the widget tree.
As such, depending on what BuildContext
you use, the call Scaffold.of(context)
may behave differently.
In your following example:
class MyScreen extends StatelessWidget {
build(BuildContext context) {
return Scaffold(
body: RaisedButton(
child: Text('push me'),
onPressed: () => Scaffold.of(context).showSnackBar(
SnackBar(content: Text('this will work'))),
),
),
);
}
}
Here, you are using the BuildContext
of MyScreen
. The issue is MyScreen
is the widget that creates Scaffold
. As such, MyScreen
is an ancestor of Scaffold
and cannot access it through Scaffold.of(context)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.