一般提到 flutter 的生命周期吁恍,有 App 的生命周期和StatefulWidget 生命周期兩個概念颇象。本文只討論 StatefulWidget 的生命周期。
StatefulWidget 生命周期指的是 StatefulWidget 從創(chuàng)建到銷毀的過程敛纲,實(shí)際上體現(xiàn)在 State 類的的方法的調(diào)用順序和調(diào)用時機(jī)掠兄。
1.createState
createState 是 StatefulWidget 創(chuàng)建 State 的方法像云。從 State 的角度來說锌雀,這個方法是個構(gòu)造方法,只會調(diào)用一次迅诬。
但是從 StatefulWidget 角度來說腋逆,這個方法會在 StatefulWidget 的生命周期里調(diào)用多次,如果 StatefulWidget 在樹的不同位置侈贷,framework 會調(diào)用 createState 多次來創(chuàng)建不同的 State惩歉。如果StatefulWidget從樹中移除再插入樹的話,framework 會調(diào)用 createState 來刷新 State俏蛮。
調(diào)用時機(jī):當(dāng) StatefulWidget 插入樹中調(diào)用撑蚌。
/// The framework can call this method multiple times over the lifetime of
/// a [StatefulWidget]. For example, if the widget is inserted into the tree
/// in multiple locations, the framework will create a separate [State] object
/// for each location. Similarly, if the widget is removed from the tree and
/// later inserted into the tree again, the framework will call [createState]
/// again to create a fresh [State] object, simplifying the lifecycle of
/// [State] objects.
2.initState
initState 是在 createState 之后調(diào)用,只會調(diào)用一次搏屑,一般只在這里執(zhí)行只需要調(diào)用一次的初始化方法争涌,例如訂閱者。
/// * In [initState], subscribe to the object.
/// * In [didUpdateWidget] unsubscribe from the old object and subscribe
/// to the new one if the updated widget configuration requires
/// replacing the object.
/// * In [dispose], unsubscribe from the object.
3. didChangeDependencies
didChangeDependencies 在 initState 之后調(diào)用辣恋,如果調(diào)用了 [BuildContext.dependOnInheritedWidgetOfExactType]
方法亮垫,InheritedWidget 在數(shù)據(jù)改變時也會調(diào)用 didChangeDependencies 方法。
4.build
build() 主要是用于構(gòu)建 widget 子樹的伟骨,會在如下場景被調(diào)用:
在調(diào)用initState()之后包警。
在調(diào)用didUpdateWidget()之后。
在調(diào)用setState()之后底靠。
在調(diào)用didChangeDependencies()之后害晦。
在State對象從樹中一個位置移除后,又重新插入到樹的其他位置之后。
/// The framework calls this method in a number of different situations. For
/// example:
///
/// * After calling [initState].
/// * After calling [didUpdateWidget].
/// * After receiving a call to [setState].
/// * After a dependency of this [State] object changes (e.g., an
/// [InheritedWidget] referenced by the previous [build] changes).
/// * After calling [deactivate] and then reinserting the [State] object into
/// the tree at another location.
5.didUpdateWidget
當(dāng) widget 需要更新的時候會調(diào)用次方法暑中,將 widget 屬性和新的 widget 綁定壹瘟,在這里對 widget 屬性的更新做處理,此方法執(zhí)行后會調(diào)用build方法鳄逾,所以無需調(diào)用 setState稻轨。
6.reassemble
reassemble 只在熱重載(hot reload)時會被調(diào)用,此回調(diào)在Release模式下永遠(yuǎn)不會被調(diào)用雕凹∨咕悖可以調(diào)試的時候?qū)?shù)據(jù)進(jìn)行重新初始化的操作。
7.deactivate
當(dāng) State 從樹中移除的時候調(diào)用枚抵。
8.activate
activate 是在 deactivate 之后重新插入樹時調(diào)用线欲。一般發(fā)生在使用 GlobalKey 從樹的某一個位置移動到另一個位置。在調(diào)用完activate后會自動調(diào) build 方法重建汽摹。
9.dispose
dispose當(dāng) State 永久的從樹中移除的時候會調(diào)用李丰。mounted
會變?yōu)閒alse,無法調(diào)用setState
,在此方法需要釋放掉持有的資源逼泣。