Flutter Getting Started and Advanced Journey (21) The Life Cycle of Flutter Components

Preface

In the previous chapters, we have systematically consolidated learning from basic components to high-order components of Flutter from shallow to deep, including data storage in Flutter, network requests, and using routing to transfer values ​​when switching pages. After this In this series of knowledge system learning and consolidation, we have basically finished learning all the knowledge needed to get started with Flutter. Today we will do a consolidated and improved sharing based on the previous courses to explore the life cycle of components in Flutter.

Course objectives

  • Master the entire life cycle process of components
  • Master the calling timing and significance of each life cycle callback function
  • Can reasonably combine the life cycle of components to improve business needs

1 What is the component life cycle?

Friends who are familiar with mobile development will be familiar with the concept of life cycle. For example, life cycle is a concept in Android, iOS, React, and Vue. It defines the state of a component from initialization to loading to intermediate transition state. The entire series of existence processes that change until they are destroyed.

Life cycle status flow chart

Combined with the above flow chart, each life cycle segment defined in Flutter can be briefly summarized into three major stages:

  • initialization
  • status change
  • destroy

2. Explanation of the significance of each life cycle stage

1. createState

createState is the method to create State in StatefulWidget. When a new StatefulWidget is to be created, createState will be executed immediately and only once. createState must be implemented:

class LifeCycleDemo extends StatefulWidget {
    
    
  @override
  State<StatefulWidget> createState() => _LifeCycleState();
}
2. initState

The previous createState is called when creating a StatefulWidget. initState is the first method called after the StatefulWidget is created, and it is only executed once, similar to Android's onCreate and IOS's viewDidLoad(), so the View is not rendered here. But at this time, StatefulWidget has been loaded into the rendering tree. At this time, the value of mount of StatefulWidget will change to true, and it will not change to false until dispose is called. You can do some initialization operations in initState.

3. didChangeDependencies

When the StatefulWidget is first created, the didChangeDependencies method will be called immediately after the initState method. Later, when the StatefulWidget is refreshed, it will not be called. Unless the InheritedWidget that your StatefulWidget depends on changes, didChangeDependencies will not be called, so didChangeDependencies It may be called multiple times.

4. build

When StatefulWidget is first created, the build method will be called immediately after the didChangeDependencies method. Another scenario where the build method will be called is that whenever the UI needs to be re-rendered, build will be called, so build will be called multiple times. Called and then returns the Widget to be rendered. Never do anything other than creating a Widget in the build, because this will affect the rendering efficiency of the UI.

5. didUpdateWidget

We generally do not use this life cycle of didUpdateWidget. It will only be called when using key to reuse Widget.

6. deactivate

When the State object is to be removed from the rendering tree, the deactivate life cycle will be called, which indicates that the StatefulWidget will be destroyed, but sometimes the State will not be destroyed, but will be re-inserted into the rendering tree.

7. dispose

When the View no longer needs to be displayed and is removed from the rendering tree, the State will be permanently removed from the rendering tree and the dispose life cycle will be called. At this time, you can do some operations to cancel monitoring and animation in dispose. , which is the opposite of initState.

3. Example code explanation

Let's use a simple example to record the entire life cycle change process of components in Flutter from 被加载to to 状态改变.被移除
Insert image description here

Sample code
import 'package:flutter/material.dart';

class LifeCycleDemo extends StatefulWidget {
    
    
  @override
  State<StatefulWidget> createState() => _LifeCycleState();
}

class _LifeCycleState extends State<LifeCycleDemo> {
    
    

  var _count = 0;

  @override
  void initState() {
    
    
    super.initState();
    print('----------initState------------');
  }

  @override
  void didChangeDependencies() {
    
    
    super.didChangeDependencies();
    print('----------didChangeDependencies------------');
  }

  @override
  Widget build(BuildContext context) {
    
    
    print('----------build------------');
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(
              child: Text('关闭页面'),
              onPressed: () => {
    
    Navigator.of(context).pop()},
            ),
            Text('当前计数器数量 : '+_count.toString()),
            RaisedButton(
              child: Text('刷新界面'),
              onPressed: () => {
    
    
                this.setState(() {
    
    
                  _count++;
                  print('----------刷新界面------------');
                })
              },
            )
          ],
        ),
      ),
    );
  }

  @override
  void deactivate() {
    
    
    super.deactivate();
    print('----------deactivate------------');
  }

  @override
  void dispose() {
    
    
    super.dispose();
    print('----------dispose------------');
  }

  @override
  void didUpdateWidget(LifeCycleDemo oldWidget) {
    
    
    super.didUpdateWidget(oldWidget);
    print('----------didUpdateWidget------------');
  }
}
3.1 When the page is loaded:

Through the above code, we simulate that when a simple component is loaded onto the page, from initialization to after the entire program is rendered, the component goes through the process from initState–>didChangeDependencies–>build . If the component does not update state at this time, operation, the interface will remain in the state after the build rendering is completed, and the log corresponding to each life cycle callback function is printed as follows:
Insert image description here

3.2 When the component is refreshed

We know that Flutter StatefulWidgetmanages Statethe state changes of the entire page. When statea change occurs, the corresponding component is notified in time. When the page state is updated, the build callback function in the life cycle will be re-awakened and the interface will be re-rendered. Changes to component status are updated and rendered to the UI in a timely manner.
Insert image description here

As shown in the picture above, when I click the refresh interface button twice, the value is setStatechanged _count, and then the component senses that the state has changed, calls the build function again, and refreshes the interface until the new state is rendered on the UI.

The log printed by the console is as follows:
Insert image description here

3. When the component is unloaded (destroyed)

When the page is destroyed, the component's life cycle state changes from deactivate–>dispose. This process is mostly a Navigator.of(context).pop()callback that occurs after the user clicks return or calls a route to push out the current page. At this time, users can perform some operations to cancel monitoring and animation according to specific business needs.
Insert image description here

3 Conclusion

Through the explanation of the existence significance of each life cycle function at the beginning, readers can use the sample code of the above life cycle test to rewrite the sample code by themselves, and feel the significance of the existence of the component life cycle and the timing of callbacks of different life cycle callback functions to deepen the understanding of the life cycle function. understand.

Guess you like

Origin blog.csdn.net/xieluoxixi/article/details/111867940