If you're just picked up flutter, you must have written the word buildcontext more than a dozen times. If you don't know what it means and what it does, here's a quick explanation for you
Widget trees
While learning flutter, you must have been told that everything in flutter is a widget, this is true to some extent but that is out of context here. These widgets are stacked together to form a widget tree. Let's take vuejs for example. You build micro components and stack them together to form a single tree, same in react, svelte, angular and so on.
Applying this ideology in flutter, your texts, buttons, cards, columns all form the widget tree, with some members having sub trees. You cant have a tree without a root, and in our case a root widget. From these root widget we stack our small widgets to form our app.
Each widget has its own buildcontext. The text, button scaffold all have a unique buildcontext once created. This buildcontext is used to to track each widget in the tree and locate them and their position in the tree.
In our basic example below,
Scaffold(
body: Center(
child: Text("Home"),
),
),
);
the Scaffold is the root widget with its unique buildcontext, its descendant the center widget has its unique buildcontext and same goes for the Text widget inside the center widget.
The widget tree rendered by a widget is returned from the build method, so for our previous stack, its build function returns it's widget tree alongside its buildcontext in order.
build(BuildContext context) {
return Scaffold(
body: Container(
child: Text("You are Logged in succesfully"),
),
),
);
}
For basic projects like the counter app, the root widget will be the MyApp widget and from it comes the widget tree. The picture below is a profiler and debugger for dart called. For better performance while coding, start by installing the flutter and dart extensions on vscode.
We have seen that BuildContext is crucial in understanding how Flutter works. It helps to order our widget tree behind the scene in their hierarchical order. To build apps confidently, we need to understand every single concept of the flutter framework.
Follow me on GitHub for real implementations on flutter, vuejs and your favorite frameworks
Top comments (0)