What exactly is BuildContext?

The downside of learning Flutter or any other framework by watching a youtube video is you don't exactly know why we use certain widgets and elements.
For instance, if I ask you exactly why we use keys in Flutter, most beginner Flutter developers would not be able to answer this question.

Flutter uses keys to store the widget's state when the user moves from one branch of the Widget tree to another, mostly used with stateful widgets.

Coming back to BuildContext

The above picture contains BuildContext you can see that we initialize it in the build method. We need this context for Navigator, MediaQuery, ListView builder, and almost all of the builders in Flutter. But why do we need it?

Widgets are a blueprint of what UI should look like at a particular part.
Often times Widgets are used alongside other widgets. But How does a Widget know where it is in relation to other widgets? It doesn't.
Note: The widget doesn't know where its instance is located it itself doesn't store any information regarding this.

So how does it works?

First, we need to understand where we use Context exactly, we use it in Stateless or stateful widgets.

Let's get into detail about it.

Let's discuss this using StatefulWidget, as you can see Stateful Widget extends Widget which means it itself is a Widget.

Let's get into Widget and check its list of methods.

If you look into Widget it has almost all the similar properties which you can find in other Flutter widgets but one, in particular, is really important. And yes it's the createElement method. This method creates Elements and these elements are the objects that are responsible to keep track of where a widget is and therefore where its parent and children are.

When you build a new widget, the Flutter framework calls that createElement method, the element it returns maintain information that is needed at runtime to understand where a widget lies in that part of the screen.

Okay, but why use BuildContext?

To understand this, for the final time let's get into Element and see what exactly it is.

And here it is, Element is actually a type of BuildContext.

Next time, whenever you use BuildContext remember that it is a way for widgets to understand where exactly they are in that part of the screen.

I referred to this video by the Flutter team to write this article.
https://youtu.be/rIaaH87z1-g