Reputation: 4849
I am following flutter's documentation about the BuildContext class because it is not clear for me how and why to use this class.
Widget build(BuildContext context) {
// here, Scaffold.of(context) returns null
return Scaffold(
appBar: AppBar(title: Text('Demo')),
body: Builder(
builder: (BuildContext context) {
return FlatButton(
child: Text('BUTTON'),
onPressed: () {
// here, Scaffold.of(context) returns the locally created Scaffold
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Hello.')
));
}
);
}
)
);
}
I do not get this paragraph:
The BuildContext for a particular widget can change location over time as the widget is moved around the tree. Because of this, values returned from the methods on this class should not be cached beyond the execution of a single synchronous function.
BuildContext objects are actually Element objects. The BuildContext interface is used to discourage direct manipulation of Element objects.
as the widget is moved around the tree -> how does this happen?
As per my understanding (and please correct me if I am wrong here) the widget tree is basically how the widgets are "stacked" and how they build each other. Since it is not recommended to have sub-widgets referenced as properties in your CustomWidget class how do I change the position in a tree of a widget returned during the build method (or how does this happen by default because of the framework)
Upvotes: 0
Views: 314
Reputation: 277487
This tree change typically happens when the build method conditionally build its descendants
Example:
Widget build(BuildContext context) {
return condition
? Foo()
: Bar(child: Foo());
}
With such build method, the BuildContext of the Foo
widget changes when condition
changes.
Upvotes: 1