TL;DR:
Is it the second parameter of build method or, name declaration of the BuildContext parameter in a conventional way?
I'm learning the basic syntax of build method in Flutter by breaking down each element of "Widget build(BuildContext context)".
My understanding so far is below:
@override: annotation
Widget build() {}: build method returns a widget
- BuildContext: a parameter/argument that contains information about the location in the tree at which this widget is being built
However, it's not been clear what the last word "context" exactly means even after I read related SO questions and official documents.
What I made sure so far is that the name "context" is changeable to whatever you want, meaning it doesn't have to be the same name as "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.
A context is nothing else but a reference to the location of a Widget within the tree structure of all the Widgets which are built. In short, think of a context as the part of Widgets tree where the Widget is attached to this tree. A context only belongs to one widget.
Each widget has its own BuildContext, which becomes the parent of the widget returned by the StatelessWidget.
From the docs, BuildContext
is:
A handle to the location of a widget in the widget tree.
context
is a BuildContext
instance which gets passed to the builder of a widget in order to let it know where it is inside the Widget Tree of your app.
One of the common uses is passing it to the of
method when using an Inherited Widget.
Calling Something.of(context)
, for example, returns the Something
relative to the closest widget in the tree that can provide you that Something
.
You can read more about BuildContext
here in the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With