Widget life cycle of the Flutter series

PS: Your plan is perfect, but the world is changing too fast.

In the last article, I learned about image loading and source code analysis in Flutter. Friends who have done mobile development know the life cycle of components. The same is true in Flutter. It is very important to understand and learn the life cycle of components in Flutter. The same series of articles as follows:

This article will mainly introduce the life cycle of Widget in Flutter, as follows:

  1. StatelessWidget
  2. StatefulWidget
  3. State life cycle state
  4. State life cycle method

StatelessWidget

The component derived from StatelessWidget is a stateless component. The stateless component is only rendered once during construction and does not support dynamic changes, that is, the component cannot be redrawn through other user operations, and can only be constructed by receiving the incoming parameters, as follows:

/// StatelessWidget
/// 表示无状态Widget
class StatelessSamplePage extends StatelessWidget {
    
    

  // 外部传入数据
  final String data;
  StatelessSamplePage(this.data);

  @override
  Widget build(BuildContext context) {
    
    
    return Container(
      color: Colors.lightBlue,
      child: Text(data),
    );
  }
}

The parameters passed in above can only be modified with final, otherwise the following warning will appear:

This class (or a class which this class inherits from) is marked as '@immutable', but one or more of its instance fields are not final: StatelessSamplePage.data

Prompt that Widget is decorated by @immutable annotation, as follows:

@immutable
abstract class Widget extends DiagnosticableTree {
    
    

At this time, only final can be used to modify the variable, and the final modified variable in Dart can only be initialized once, which also conforms to the stateless feature of StatelessWidget.

StatefulWidget

StatefulWidget-derived components are stateful components, and stateful components support multiple construction of Widgets as data changes to complete the rendering of dynamic interfaces. If you want to implement an interface that displays the current time in real time, Obviously StatelessWidget cannot be completed. Use the stateful StatefulWidget to achieve, as follows:

/// StatefulWidget
/// 表示有状态的 Widget
class StatefulSamplePage extends StatefulWidget {
    
    
  @override
  _StatefulSamplePageState createState() => _StatefulSamplePageState();
}

class _StatefulSamplePageState extends State<StatefulSamplePage> {
    
    
  DateFormat _dateFormat;
  String _currentTime;
  Timer _timer;

  @override
  void initState() {
    
    
    super.initState();
    _dateFormat = new DateFormat("yyyy-MM-dd HH:mm:ss");
    // 初始化当前时间
    _currentTime = _dateFormat.format(DateTime.now());
    // 更新时间
    _startTime();
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Center(
      child: Scaffold(
        appBar: AppBar(
          title: Text("Stateful Widget sample"),
          centerTitle: true,
        ),
        body: Align(
          alignment: Alignment.topCenter,
          child: Text("当前时间:$_currentTime"),
        ),
      ),
    );
  }

  @override
  void dispose() {
    
    
    super.dispose();
    if(_timer!=null){
    
    
      _timer.cancel();
    }
  }

  _startTime() {
    
    
    const Duration duration = Duration(seconds: 1);
    _timer = Timer.periodic(
        duration,
        (Timer timer) => {
    
    
              // 刷新界面状态
              setState(() {
    
    
                _currentTime = _dateFormat.format(DateTime.now());
              })
            });
  }
}

The effect is as follows:

In fact, if only the static interface StatelessWidget and StatefulWidget are completely indistinguishable, they are both achievable. The only difference is that StatefulWidget can trigger the rebuilding of Widget through the setState method. The State class is the bridge between Stateless -> Stateful.

State life cycle state

Flutter life cycle is actually the life cycle of each component:

  • StatelessWidget: The life cycle of a stateless component is only the build process;
  • StatefulWidget: The life cycle of a stateless component refers to the life cycle of State.

The life cycle of Flutter is actually the life cycle of stateless components, that is, the life cycle of State, as shown in the following figure:

State life cycle state

As above, the life cycle states of each State are mainly three:

  • created: refers to the creation state of the State, it is in the created state when the createState method is called;
  • Dirty: refers to the state when the data of the method such as setState is called, but the Widget has not been rebuilt;
  • clean: refers to the state after the Widget is constructed;
  • Defunct: Refers to the state after State.dispose is called. At this time, the corresponding Widget has been destroyed and cannot be rebuilt.

State life cycle method

The life cycle of a stateful component is the life cycle of State. The specific call process and build trigger timing are shown in the following figure:

State life cycle method

The specific meaning of its life cycle method is as follows:

  • createState: Used to create State in StatefulWidget;
  • initState: State initialization operations, such as variable initialization, etc.;
  • didChangeDependencies: Called after initState is called, or if the InheritedWidgets component is used, InheritedWidgets can be used for Flutter state management;
  • build: used for the construction of Widget;
  • deactivate: Called after the Widget containing this State object is removed. If the Widget is not added to the tree structure of other Widgets after being removed, the dispose method will continue to be called;
  • dispose: Release the resources occupied by the Widget after the method is called;
  • reassemble: used in the development phase, it will be called during hot reloading, and will be rebuilt afterwards;
  • didUpdateWidget: The didUpdateWidget method of the child Widget will be called when the parent Widget is built.

Add a log to the corresponding Widget life cycle method to verify the execution of the above life cycle method. The parent Widget source code is as follows:

const String TAG = "Flutter";
/// Widget生命周期
class WidgetLifecycleSamplePage extends StatefulWidget {
    
    
  @override
  _WidgetLifecycleSamplePageState createState() {
    
    
    Log.info(TAG, "parent createState");
    return _WidgetLifecycleSamplePageState();
  }
}

class _WidgetLifecycleSamplePageState extends State<WidgetLifecycleSamplePage> {
    
    

  num _count = 0;

  @override
  void initState() {
    
    
    super.initState();
    Log.info(TAG, "parent initState");
  }

  @override
  Widget build(BuildContext context) {
    
    
    Log.info(TAG, "parent build");
    return Scaffold(
      appBar: AppBar(
        title: Text("Widget Lifecycle Sample"),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: RaisedButton(
                textColor:Colors.white,
                color: Colors.lightBlue,
                child: Text("parent->setState:$_count",style: TextStyle(color: Colors.white),),
                onPressed: (){
    
    
                  setState(() {
    
    
                    Log.info(TAG, "parent setState");
                    _count++;
                  });
                }),
          ),
          SubWidgetLifecycleSamplePage(),
        ],
      )
    );
  }

  @override
  void didUpdateWidget(WidgetLifecycleSamplePage oldWidget) {
    
    
    super.didUpdateWidget(oldWidget);
    Log.info(TAG, "parent didUpdateWidget");
  }

  @override
  void didChangeDependencies() {
    
    
    super.didChangeDependencies();
    Log.info(TAG, "parent didChangeDependencies");
  }

  @override
  void deactivate() {
    
    
    super.deactivate();
    Log.info(TAG, "parent deactivate");
  }

  @override
  void reassemble() {
    
    
    super.reassemble();
    Log.info(TAG, "parent reassemble");
  }

  @override
  void dispose() {
    
    
    super.dispose();
    Log.info(TAG, "parent dispose");
  }
}

/// 子Widget
class SubWidgetLifecycleSamplePage extends StatefulWidget {
    
    
  @override
  _SubWidgetLifecycleSamplePageState createState() {
    
    
    Log.info(TAG, "sub createState");
    return _SubWidgetLifecycleSamplePageState();
  }
}

The implementation of the child Widget is similar to the implementation of the parent Widget and will not be posted. You can reply to the keyword [Lifecycle] in the background of the official account to obtain the complete source code. The above code display effect is as follows:

The corresponding method calls of the life cycle are as follows:

analyse as below:

  1. The Widget initialization process refers to the life cycle process of entering the page where Widge is located, first the parent Widget and then the child Widget, and then call the createState, initState, didChangeDepandencies, and build methods in turn;
  2. When the parent Widget seteState updates the data, the construction of the parent Widget is triggered, so the child Widget calls the didUpdateWidget method;
  3. Other processes such as hot reload and Widget destruction are the same as the flow chart of the State life cycle method above, so I won't repeat them here.

You can reply to the keyword [Lifecycle] in the backstage of the official account to obtain the completed source code. For more information, please refer to the WeChat official account .

Insert picture description here

Guess you like

Origin blog.csdn.net/jzman/article/details/112454883
Recommended