I've noticed that a state's build method passes in a BuildContext, and I've also noticed that the State itself also has a member called context. I was wondering when it's appropriate to use the BuildContext, and when is it appropriate to use the member variable? Are they interchangeable?
Are there times when using one over the other can cause errors and how do we take measures to insure we don't do this?
BuildContext is a locator that is used to track each widget in a tree and locate them and their position in the tree. The BuildContext of each widget is passed to their build method. Remember that the build method returns the widget tree a widget renders. Each BuildContext is unique to a widget.
– Context is a link to the location of a widget in the tree structure of widgets. – Context can belong to only one widget. – If a widget has child widgets, then the context of the parent widget becomes the parent context for the contexts of direct child elements.
From the flutter documentation for State
and the build function:
The BuildContext argument is always the same as the context property of this State object and will remain the same for the lifetime of this object. The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.
They are strictly equal.
It may not be obvious, but the BuildContext
passed as parameter to build
never ever change.
The context
field of State
is only pointing to that constant BuildContext
.
Why a duplicate ? Because StatefulWidgets
tend to update over time.
So you may need to access this BuildContext
inside methods such as didUpdateWidget
.
StatelessWidget
doesn't need that because it only as a build
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With