The Purpose Of BuildContext
Most of the times while developing applications in Flutter we noticed the term BuildContext. It is the most common and most useful knowledge base topic while developing UI’s.
Most of the developers even seasoned ones find hardest to understand the concept behind BuildContext. Lets Start in flutter way.
First we have to acknowledge what the term Widget Tree is :
Widget Tree
In flutter you hear widget is everything.
The Widget tree is just a representation of the configuration of the widget. Flutter Framework creates an Element tree from the information available in the Widget Tree and inflates the Element object with the Widget.
“Widget(s) always organized in a tree structure”
since the location of a particular widget also matters alot. Widget tree is nothing but a stack of Widgets locate accordingly to their positions in user interface. Lets assume :
In this tree MyApp contain the widget Container, Container itself contains a widget Column and so on. So this is the Widget tree in User interface. Lets move on to the justification of BuildContext….
BuildContext
BuildContext is a reference to a widget in a tree. Like it is a locator used to track each widget in a widget tree and locate according to there position.
Note that each widget has a particular BuildContext and it is unique in tree position.
The actual syntax looks like:
@override
Widget build(BuildContext context) {
// ..
Useful Method
1 : context.AncestorWidgetOfExactType( );
Here the method invoke the exact type according to the position of the widget. It always return the nearest ancestor widget
An example is, considering the Scaffold -> Center -> Column -> Text:
context.AncestorWidgetOfExactType(Scaffold) => returns the first Scaffold by going up to tree structure from the Text context.
2 : context.dependOnInheritedWidgetOfExactType( );
It obtains the nearest widget of the given type T, which must be the type of a concrete InheritedWidget subclass, and registers this build context with that widget such that when that widget changes. [By using provider SM]
The main purpose of BuildContext is
To interact with the parent widget
Once get the screen size and layout(very rare)
Here another example
When you want to push a new route you’ll do:
Notice the context here, it will be used to get the closest instance of NavigatorState widget above the tree. Then call the method pushNamed on that instance.
I think this would be enough for the basic understanding of BuildContext.