Note: This article has authorized the wechat public account Flutter to publish exclusively, without authorization, it is strictly prohibited to republish!
1. Preface Before learning a new technology, we always need to understand the most basic things, just like when contacting Android, we have to learn the four components for a long time. Do you still remember the life cycle of Android? Let’s start by reviewing the life cycle in Android
1. Start the Activity: the system calls onCreate, onStart, and onResume to start the Activity. 2. The current Activity is overwritten by another Activity or the screen is locked: The system calls the onPause method to pause the Activity. 3. The current Activity returns to the foreground or unlock screen after being overwritten: the system calls onResume to start the Activity again. 4. The current Activity moves to a new Activity screen or returns to the Home screen by pressing the Home button. The system calls onPause and then onStop to enter the pause state. 5. The user steps back to the Activity: the system calls the onRestart method, then the onStart method, and finally the onResume method to start the Activity again. 6. The current Activity is overwritten or not visible in the background, that is, in step 2 and step 4, the system is out of memory, kill the current Activity, and then the user returns to the current Activity: call onCreate, onStart, and onResume methods again to enter the running state. 7. The user exits the current Activity: the system calls onPause, onStop, and onDestory to end the current Activity.Copy the code
Emmm, I’m sure you’ll remember by now, foreplay is over, let’s get to the point and talk about our hero today, “State”.
Before our hero comes on the scene, let’s get to know his little friend
Almost all objects in A Flutter are widgets. Unlike the "controls" in native development, widgets in A Flutter are broader in concept. They can represent not only UI elements but also functional components such as: GestureDetector Widget for gesture detection, Theme for application Theme data delivery, and more. Controls in native development are usually just UI elementsCopy the code
3. Introduction of State
- StatelessWidget(for scenarios where no state needs to be maintained)
abstract class StatelessWidget extends Widget
Copy the code
- StatefulWidget(for scenarios where state needs to be maintained)
abstract class StatefulWidget extends Widget
Copy the code
From the above code we can see that they all inherit a Widget, so take a quick look at the class
@immutable
abstract class Widget extends DiagnosticableTree {
const Widget({ this.key });
final Key key;
@protected
Element createElement(a);
@override
String toStringShort(a) {
return key == null ? '$runtimeType' : '$runtimeType-$key';
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.defaultDiagnosticsTreeStyle = DiagnosticsTreeStyle.dense;
}
static bool canUpdate(Widget oldWidget, Widget newWidget) {
returnoldWidget.runtimeType == newWidget.runtimeType && oldWidget.key == newWidget.key; }}Copy the code
There is a common method in the code above, a method that needs to be overridden every time we inherit
@override
StatefulElement createElement(a) => StatefulElement(this);
Copy the code
Continue tracing StatefulElement and find a * widget.creatEstate ()* method. If you find one, continue
class StatefulElement extends ComponentElement {
/// Creates an element that uses the given widget as its configuration.
StatefulElement(StatefulWidget widget)
: _state = widget.createState(),
super(widget) {
.....
assert(_state._element == null);
_state._element = this;
assert(_state._widget == null);
_state._widget = widget;
assert(_state._debugLifecycleState == _StateLifecycle.created);
}
Copy the code
Click on the createState method and we finally find the hero of the day. Yes, that’s it, State, can’t escape.
@protected
State createState(a);
Copy the code
- At this point, we have found what we want. As mentioned earlier,Android has its own life cycle, so Flutter has its own unique life cycle
Yeah, I saw it right awayinitStateThis method, remember in network requests or initialization of variables, is always written to this method
@override
void initState(a) {
// TODO: implement initState
super.initState();
_loadItemPage();
}
Copy the code
We can divide the above methods into three parts for description, as shown in the following figure:
- Initialize (insert render tree)
The constructor
Not lifecycle, because the widget property of State is empty and the widget property cannot be accessed in the constructorCopy the code
- initState
/// Called when this object is inserted into the tree. This function is called only once in its life cycle. Here you can do some initialization, such as initializing the State variableCopy the code
- didChangeDependencies
/// Called when a dependency of this [State] object changes. This function is called immediately after initStateCopy the code
- State changes (present in the render tree)
- didUpdateWidget
/// Called whenever the widget configuration changes. DidUpdateWidget is called when the component's state changes, such as when it is calledsetStat
Copy the code
- Destroy (remove from render tree)
- deactivate
/// Called when this object is removed from the tree. This function is called before Dispose.Copy the code
- dispose
/// Called when this object is removed from the tree permanently. Once the component is destroyed at this stage, this function typically removes listeners and cleans up the environment.Copy the code
This function is called only once in its life cycle. Here you can do some initialization, such as initializing the State variable.
I’ll do it in general, and then I’ll summarize it with a graph
phase | Call the number | Whether setState is supported |
---|---|---|
The constructor | 1 | no |
initState | 1 | Supported but not valid (same as not using setState) |
didChangeDependencies | > = 1 | Supported but invalid |
didUpdateWidget | > = 1 | Supported but invalid |
deactivate | > = 1 | no |
dispose | 1 | no |
- Some people may say, BB so long, MAO did not see a root, so talk about so much, not to point to the actual how to live before bb? Somebody, get in the code
import 'package:flutter/material.dart';
class LifeState extends StatefulWidget {
@override
_lifeStates createState(a) => _lifeStates();
}
class _lifeStates extends State<LifeState> {
@override
void initState(a) {
// TODO: implement initState
super.initState();
print('initState');
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
print(state.toString());
}
@override
void didChangeDependencies(a) {
// TODO: implement didChangeDependencies
super.didChangeDependencies();
print('didChangeDependencies');
}
@override
void didUpdateWidget(LifeState oldWidget) {
super.didUpdateWidget(oldWidget);
print('didUpdateWidget');
}
@override
Widget build(BuildContext context) {
print('build');
// TODO: implement build
return MaterialApp(
home: Center(
child: GestureDetector(
child: new Text('lifeCycle'),
onTap: () {
Navigator.of(context)
.push(new MaterialPageRoute(builder: (BuildContext c) {
return new Text('sdfs'); })); },))); }@override
void reassemble(a) {
// TODO: implement reassemble
super.reassemble();
print('reassemble');
}
@override
void deactivate(a) {
// TODO: implement deactivate
super.deactivate();
print('deactivate');
}
@override
void dispose(a) {
// TODO: implement dispose
super.dispose();
print('dispose'); }}Copy the code
The test results
- Create a widget
initState
didChangeDependencies
build
Copy the code
- Exit pages
deactivate
dispose
Copy the code
- Click the hot load button
reassemble
didUpdateWidget
build
Copy the code
- App from Display to background (Home button)
AppLifecycleState.inactive
AppLifecycleState.paused
Copy the code
- App goes from the background back to the foreground
AppLifecycleState.inactive
AppLifecycleState.resumed
Copy the code