skip to Main Content

When creating a widget, which parameter is used to access the parent’s BuildContext?

  1. context
  2. widgetContext
  3. parentContext
  4. 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


  1. 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.

    Login or Signup to reply.
  2. 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:

    return Scaffold(
      body: Container(
        color: Colors.blue,
      ),
      floatingActionButton: FloatingActionButton(onPressed: () {
        Scaffold.of(context).showSnackBar(SnackBar(content: Text("Hello")));
      }),
    // Other code
    );
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search