When creating a widget, which parameter is used to access the parent’s BuildContext?
- context
- widgetContext
- parentContext
- buildContext
I found this question has various answers. So I try to find the right answers. Can you give me the right answers with example.
2
Answers
It’s typically "context" but it could be whatever you want to call it. It’s the first and only positional parameter to your build method. It is of type BuildContext.
The context passed down in the build method references the widget that is one above the current widget in the widget tree (essentially the parent).
So, for example if you do something like this:
This will throw an error on "Scaffold.of(context)" line that there is no Scaffold widget in the widget tree. Why? Because the context passed down the build method essentially refers to the parent widget, which doesn’t have a Scaffold widget. The Scaffold widget is defined in the current build method so, only the children of this widget can access the Scaffold from their context.