What does BuildContext do in Flutter?

后端 未结 3 1372
后悔当初
后悔当初 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: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

提交回复
热议问题