Home > Net >  Where is "context" argument coming from in build?
Where is "context" argument coming from in build?

Time:06-12

I'm still new to Flutter and I don't seem to understand where arguments are coming from in a few cases. I see a few cases where I'm passing a parameter but I have no idea where that parameter is coming from. For example...

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
          primaryColor: Colors.lightBlue,
          scaffoldBackgroundColor: Colors.white),
      home: PriceScreen(),
    );
  }
}

Where is MyApp getting this "context" argument that it sends to the widget's build function? To my uneducated eye, "context" just looks like an undeclared variable. Another example is passing a value to a dropdown...

child: DropdownButton<String>(
    value: selectedValue,
    items: getDropdownItems(),
    onChanged: (value) {
      setState(() {
        selectedValue = value;
      });
    }),

Where am I getting "value" from? I haven't declared anything called "value" so I don't understand where it is coming from or how it is supplied. I have looked at the typedef and found typedef ValueChanged<T> = void Function(T value); so I can understand that it expects a value but I just don't really get where it comes from so that I can pass it as an argument.

CodePudding user response:

For the getting context It is coming from StatelessWidget in general

 @protected
 Widget build(BuildContext context);

An example can of abstract-classes

abstract class A {
  void method(int v);
}

class B extends A {
  @override
  void method(int v) {}
}

And typedefs is a smart way of using callback methods. In general, It will

class C {
  final Function(int value) callback;
  C({required this.callback});
}

And if you use this class you will get value

 C(callback: (value) {});

You can check more about dart on language-tour.

CodePudding user response:

In Flutter everything is widget.

All widgets will form a tree called widget tree.

  1. Context is a link to the location of a widget in the tree structure of widgets.
  2. Context can belong to only one widget.
  3. if a widget has child widgets, then the context of the parent widget becomes the parent context for the contexts of direct child elements.

Now you know where , the contexts are coming from.

On drop down , when you select a value , it will be passed like that.

For more doubts , check the official documentations.

  • Related