What is buildcontext in flutter?

The downside of learning Flutter or any other framework by watching a video on YouTube is that you don't know exactly why we use certain widgets and elements.

For example, if I were to ask you why we use keys in Flutter, most beginner Flutter developers wouldn't be able to answer that question.





Flutter uses keys to store the state of the widget when the user transitions from one branch of the widget tree to another, primarily used with stateful widgets.

Returning to BuildContext

The image above shows the BuildContext that can be seen initialized in the build method. We need this context for Navigator, MediaQuery, ListView.builder, and almost all other constructors in Flutter. But why do we need it?

Widgets are blueprints of what the UI should look like at a given moment. Often, widgets are used in conjunction with other widgets. But how does a widget know where it is relative to other widgets? It doesn't.

Note: The widget doesn't know where its instance is located, it doesn't store any information in this regard.

So how does it work ?

First and foremost, it's important to understand where we use the context (Context) exactly. We use it in both Stateless and Stateful widgets.

Let's delve into the details of this topic:

Absolutely! Let's discuss it using StatefulWidget. As you can see, StatefulWidget extends Widget, which means it is itself a Widget.

Let's go into Widget and check its list of methods:

If you look at the Widget class, it has almost all the similar properties you can find in other Flutter widgets, but one, in particular, is really important. Yes, it's the createElement method. This method creates elements, and these elements are objects responsible for tracking where a widget is and, consequently, where its parent and children are located.

When you create a new widget, the Flutter framework calls this createElement method. The element it returns contains the necessary information at runtime to understand where the widget is on that part of the screen.

So, an Element is actually a type of BuildContext.

The next time you use BuildContext, remember that it's a way for widgets to precisely understand where they are on that part of the screen.

I referred to this video by the Flutter team while writing this article.


Post a Comment

Previous Post Next Post