What does BuildContext do in Flutter?

后端 未结 3 1364
后悔当初
后悔当初 2020-12-07 10:23

What does BuildContext do, and what information do we get out of it?

https://docs.flutter.io/flutter/widgets/BuildContext-class.html is just not clear

相关标签:
3条回答
  • 2020-12-07 10:33

    BuildContext is, like it's name is implying, the context in which a specific widget is built.

    If you ever done some React before, that context is kind of similar to React's context (but much smoother to use) ; with a few bonuses.

    Generally speaking, there are 2 uses cases for context :

    • Interact with your parents (get/post data mostly)
    • Once rendered on screen, get your screen size and position

    The second point is kinda rare. On the other hand, the first point is used nearly everywhere.

    For example, when you want to push a new route, you'll do Navigator.of(context).pushNamed('myRoute').

    Notice the context here. It'll be used to get the closest instance of NavigatorState widget above in the tree. Then call the method pushNamed on that instance.


    Cool, but when do I want to use it ?

    BuildContext is really useful when you want to pass data downward without having to manually assign it to every widgets. Configurations for example ; you'll want to access them everywhere. But you don't want to pass it on every single constructor.

    You could potentially make a global or a singleton ; but then when confs change your widgets won't automatically rebuild.

    In this case, you use InheritedWidget. With it you could potentially write the following :

    class Configuration extends InheritedWidget {
      final String myConf;
    
      const Configuration({this.myConf, Widget child}): super(child: child);
    
      @override
      bool updateShouldNotify(Configuration oldWidget) {
        return myConf != oldWidget.myConf;
      }
    }
    

    And then, use it this way :

    void main() {
      runApp(
        new Configuration(
          myConf: "Hello world",
          child: new MaterialApp(
            // usual stuff here
          ),
        ),
      );
    }
    

    Thanks to that, now everywhere inside your app, you can access these configs using the BuildContext. By doing

    final configuration = context.inheritFromWidgetOfExactType(Configuration);
    

    And even cooler is that all widgets who call inheritFromWidgetOfExactType(Configuration) will automatically rebuild when the configurations change.

    Awesome right ?

    0 讨论(0)
  • 2020-12-07 10:41

    Flutter widget tree composed of 02 types of widgets.

    1- class widget (parent widget / class extends by stateless or stateful widget)

    2- build widget (child widget / widget return by build()

    Both widgets have its own context .


    Context

    What is context really mean ????

    context is a parameter(variable) that contain value(object) ,value = location(position) this widget is built.

    Note:- This value(location) / argument for this parameter is given by Framework automatically when widget is built.; so dont think about how this parameter gets the value

    Is every widget has a build location ???

    YES ,Every widget has build location, without that location framework cannot create Element tree of that widget tree.(keep in mind it also useful for developers)

    There 02 types of context

    1 - Class widget context (parent widget)

    2 - build widget context (child widget)

    • Class widget context - This context is not visible for us,Its only use by framework itself for creating element tree.

    • build widget context - This context is visible for us , Its use by framework and also we use it some purposes (eg:- for acessing ancester widget)

    --------------------------------------------------------------------------------------

    build widget context / BuildContext context

    build widget context is the context type that you passed for build() method (As below code)

    @override
    Widget build(BuildContext context) {            //BuildContext
      return Text(
        'Example',
        style: Theme.of(context).textTheme.title,
      );
    }
    

    Everyone know that variable or parameter has its own type. (like int, double, String..etc)

    So this context parameter also has a type called "BuildContext"

    (This special name "BuildContext" well represents the meaning of that context , Because this context is owned by build method ,So it gets the name as "BuildContext")


    Where is the location of that widget

    To answer this question see below code ,it will show you the build location of that widget ( and this location is the store in context object(parameter).

    See below flutter code ,In there you can see comment //here is the location of this child widget is build..This comment denotes the build location of that child widget.

    Example code - 1

    @override
    Widget build(BuildContext context) {
      //here is the location of this child widget is build.
      return Text(
        'Example',
        style: Theme.of(context).textTheme.title,
      );
    }
    

    Example code -2

    @override
      Widget build(BuildContext context) {
        // here build location of that widget                     //here
        return Scaffold(
          appBar: AppBar(title: Text('Demo')),
          body: Builder(
            // here build location of that widget                 //here
            builder: (BuildContext context) {
              return FlatButton(
                child: Text('BUTTON'),
                onPressed: () {
                  Scaffold.of(context).showSnackBar(SnackBar(
                    content: Text('Hello.')
                  ));
                }
              );
            }
          )
        );
      }
    

    In this post i was sawing you about the meaning of context .But here i didn't show use cases of BuildContext context, But some use cases are shown by @Remi Rousselet answer.

    Hope this will help you

    0 讨论(0)
  • 2020-12-07 10:51

    BuildContext Class is nothing else but a reference to the location of a Widget within the tree structure of all the Widgets which are built.

    Every Flutter widget has an @override build() method with the argument of BuildContext.

    class CartItemWidget extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {.....
    

    Simply explain is that the BuildContext is:

    1. A BuildContext only belongs to one widget.
    2. BuildContext objects are passed to WidgetBuilder functions

    A BuildContext only belongs to one widget.

    If a widget ‘A’ has children widgets, the BuildContext of widget ‘A’ will become the parent BuildContext of the direct children BuildContexts.

    Reading this, it is clear that BuildContexts are chained and are composing a tree of BuildContexts (parent-children relationship)

    If we now try to illustrate the notion of BuildContext in the previous diagram, we obtain (still as a very simplified view) where each color represents a BuildContext (except the MyApp one, which is different):

    The following diagram shows (a simplified version of) the sequence of actions/calls related to the creation of a Stateful Widget.

    Widget’s state is independent of the parameters and yet it was getting rebuilt every time the parameters were changing. In that case, need to use InheritedWidget

    InheritedWidget is a special kind of widget that defines a context at the root of a sub-tree. It can efficiently deliver this context to every widget in that sub-tree. The access pattern would look familiar to Flutter developers:

    class MyInheritedWidget extends InheritedWidget {
    
    MyInheritedWidget({
          Key key,
          @required Widget child,
          this.data,
       }): super(key: key, child: child);
    
       final data;
    
       static MyInheritedWidget of(BuildContext context) {
          return context.inheritFromWidgetOfExactType(MyInheritedWidget);
       }
    
       @override
       bool updateShouldNotify(MyInheritedWidget oldWidget) => data != oldWidget.data;
    }
    

    The static MyInheritedWidget of(BuildContext context) method, allows all the children widgets to get the instance of the closest MyInheritedWidget” which encloses the context

    Finally, the updateShouldNotify overridden method is used to tell the InheritedWidget whether notifications will have to be passed to all the children widgets (that registered/subscribed) if a modification be applied to the data

    for more information

    1. Build Context
    2. Widget,State,BuildContext,InheritedWidget
    3. Inheriting Widgets
    0 讨论(0)
提交回复
热议问题