Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BuildContext vs State Context

Tags:

flutter

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?

like image 806
Kevin Gray Avatar asked Mar 27 '18 18:03

Kevin Gray


People also ask

What is BuildContext context?

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.

What is meant by context in flutter?

– 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.


2 Answers

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.

like image 184
rmtmckenzie Avatar answered Oct 18 '22 14:10

rmtmckenzie


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.

like image 39
Rémi Rousselet Avatar answered Oct 18 '22 13:10

Rémi Rousselet