This is the 25th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021. In iOS development, we all know the controller life cycle, from appearance to disappearance. Learn about the life cycle of our widgets in Flutter.
1. Basic concepts of Widget lifecycle
- The life cycle
The life cycle is the process from creation to destruction, and in practice is the various callback methods (function calls). The goal is to let us know what state the packaged Widget is in.
- role
We listen to the Widget’s life cycle to perform operations such as initState to initialize data: create data or send network requests. Dispose is used for memory management, data destruction, listener or Timer, etc.
2. Widget lifecycle
2.1 StatelessWidget
There is no state for statelessWidgets, so only
- Initialize the
init
Build to create
(Build is called every time the page is drawn)
2.2 StatefulWidget
Init initialization
createState
CreateState is created when the Widget’s state is created. This method is called only once
The state of the init
When we create the State, we execute the initialization method, only once
initState()
InitState is called when you create the state, and it’s only done once, usually we’re doing some data processing or some initialization here, and the view hasn’t been loaded yet, like our viewDidload.
didChangeDependencies
DidChangeDependencies is called immediately after initState and only after the InheritedWidget that StatefulWidget relies on has changed, So didChangeDependencies can be called multiple times. We’ll cover the InheritedWidget: Data sharing later
build
Build is called when the page is drawn and initialized after didChangeDependencies. SetState () is called again to render the page. Calling other methods affects rendering efficiency.
addPostFrameCallback
AddPostFrameCallback is called at the end of rendering, usually in initState, only once.
didUpdateWidget
It is called when the component is updated, usually once after the widget is initialized
deactivate
Called when a component is removed
dispose
When the Widget is destroyed, State dispose is called, which usually does some operations such as listening cancellation, timer destruction, animation, etc. Use this as opposed to init State