前言
上一篇我們講到網(wǎng)絡(luò)請(qǐng)求等異步操作最好放在 GetxController 的 onReady 生命周期函數(shù)中處理。本篇我們來(lái)介紹 GetxController 的生命周期函數(shù)。
GetxController 類
我們自定義的Controller繼承關(guān)系如下所示。
其中 GetxController只是有個(gè) update 方法用于通知組件刷新。在 DisposableInterface 中覆蓋了onInit 方法,實(shí)際多干了一件事:
SchedulerBinding.instance?.addPostFrameCallback((_) => onReady());
其實(shí)就是將 onReady 方法作為回調(diào),當(dāng) onInit 完成之后的一幀來(lái)調(diào)用 onInit。這也就是我們上一篇說(shuō)的,onReady 會(huì)在 onInit 完成后一幀后調(diào)用。這里有三個(gè)方法:
-
onInit:組件在內(nèi)存分配后會(huì)被馬上調(diào)用,可以在這個(gè)方法對(duì) controller 做一些初始化工作。 -
onReady:上一篇我們介紹過(guò),這里是在 onInit 一幀后被調(diào)用,適合做一些導(dǎo)航進(jìn)入的事件,例如對(duì)話框提示、SnackBar 或異步網(wǎng)絡(luò)請(qǐng)求。 -
onClose:在onDelete方法前調(diào)用、用于銷毀controller使用的資源,例如關(guān)閉事件監(jiān)聽(tīng),關(guān)閉流對(duì)象,或者銷毀可能造成內(nèi)存泄露的對(duì)象,例如TextEditingController,AniamtionController。也適用于將數(shù)據(jù)進(jìn)行離線持久化。
再往上是 GetLifeCycle 類,這個(gè)類只是在構(gòu)造函數(shù)中配置了生命周期,實(shí)際上也是調(diào)用到 mixin 的 GetLifeCycleBase 的$configureLifeCycle方法。實(shí)際上所有生命周期的方法都在這個(gè) mixin 的定義。具體的方法如下:
-
onStart:組件在內(nèi)存分配的時(shí)間點(diǎn)就會(huì)被調(diào)用,這是一個(gè)final方法,并使用了內(nèi)部的callable類型,以避免被子類覆蓋。 -
onDelete:也是一個(gè)final方法,類型和onStart一樣,同樣不能被覆蓋。在controller別銷毀前調(diào)用。
實(shí)際上 onStart 和 onDelete 分別綁定了內(nèi)部的_onStart 和 _onDelete 方法,在這兩個(gè)方法里調(diào)用了 onInit 和 onClose 方法。
/// 在 GetLifeCycle的構(gòu)造函數(shù)中調(diào)用
void $configureLifeCycle() {
_checkIfAlreadyConfigured();
onStart._callback = _onStart;
onDelete._callback = _onDelete;
}
bool _initialized = false;
/// Checks whether the controller has already been initialized.
bool get initialized => _initialized;
、
void _onStart() {
if (_initialized) return;
onInit();
_initialized = true;
}
bool _isClosed = false;
/// Checks whether the controller has already been closed.
bool get isClosed => _isClosed;
// Internal callback that starts the cycle of this controller.
void _onDelete() {
if (_isClosed) return;
_isClosed = true;
onClose();
}
也就是前面說(shuō)的,onStart是在controller內(nèi)存分配的時(shí)間點(diǎn) 調(diào)用的,完成內(nèi)存分配后就馬上調(diào)用了 ``
替代 StatefulWidget
有了 GetxController 的生命周期后,我們就可以完全替換掉 StatefulWidget 了。
- onInit或 onReady替換 initState,例如下面的代碼:
@override
void onInit() {
//網(wǎng)絡(luò)請(qǐng)求或其他初始化
apiService.getData();
super.onInit();
}
- onClose 替換 dispose,比如關(guān)閉流:
class Controller extends GetxController {
StreamController<String> name = StreamController<String>();
// ...
@override
void onClose() {
name.close();
super.onClose();
}
}
總結(jié)
基于上面的分析,我們得出GetxController 的生命周期及對(duì)應(yīng)說(shuō)明如下圖。
整個(gè)生命周期我們能夠接入的方法就三個(gè):
- onInit:初始化 Controller,例如一些成員屬性的初始化;
- onReady:就緒后的業(yè)務(wù)處理,如異步操作、導(dǎo)航進(jìn)入的參數(shù)處理等;
- onClose:釋放資源,避免內(nèi)存泄露,同時(shí)也可以進(jìn)行數(shù)據(jù)持久化。
通過(guò)對(duì) GetxController 的生命周期的理解,我們能夠知道每個(gè)生命周期適合做得事情。