withLifecycleEffect<T extends Object> method
T
withLifecycleEffect<T extends Object>({})
直接使用生命周期对类对象进行操作
Implementation
T withLifecycleEffect<T extends Object>({
T? data,
T Function()? factory,
T Function(Lifecycle lifecycle)? factory2,
Launcher<T>? launchOnFirstCreate,
Launcher<T>? launchOnFirstStart,
Launcher<T>? launchOnFirstResume,
Launcher<T>? repeatOnStarted,
Launcher<T>? repeatOnResumed,
Launcher<T>? launchOnDestroy,
}) {
assert(() {
if (this is LifecycleRegistryState) {
assert(currentLifecycleState > LifecycleState.initialized,
'In LifecycleRegistryState, the currentLifecycleState must be greater than LifecycleState.initialized');
} else {
assert(currentLifecycleState > LifecycleState.destroyed,
'The currentLifecycleState state must be greater than LifecycleState.destroyed.');
}
return true;
}());
if (currentLifecycleState <= LifecycleState.destroyed) {
throw 'The currentLifecycleState state must be greater than LifecycleState.destroyed.';
}
assert(data != null || factory != null || factory2 != null,
'data and factory cannot be null at the same time');
if (data == null && factory == null && factory2 == null) {
throw 'data and factory cannot be null at the same time';
}
T value = data ?? factory?.call() ?? factory2!.call(toLifecycle());
if (launchOnFirstCreate == null &&
launchOnFirstStart == null &&
launchOnFirstResume == null &&
repeatOnStarted == null &&
repeatOnResumed == null &&
launchOnDestroy == null) {
return value;
}
Lifecycle life = toLifecycle();
Map<Object, _LauncherLifecycleObserver> lifecycleEffectObservers =
life.extData.putIfAbsent(
key: _withLifecycleEffectToken, ifAbsent: () => WeakHashMap());
_LauncherLifecycleObserver<T> observer =
lifecycleEffectObservers.putIfAbsent(value as Object, () {
final o = _LauncherLifecycleObserver<T>(value);
o.launchOnFirstCreate = launchOnFirstCreate;
o.launchOnFirstStart = launchOnFirstStart;
o.launchOnFirstResume = launchOnFirstResume;
o.launchOnDestroy = launchOnDestroy;
if (repeatOnStarted != null) {
o.repeatOnStarted = repeatOnStarted;
}
if (repeatOnResumed != null) {
o.repeatOnResumed = repeatOnResumed;
}
//加入销毁的逻辑
life.addLifecycleObserver(LifecycleObserver.eventDestroy(
() => lifecycleEffectObservers.remove(value)));
life.addLifecycleObserver(o);
return o;
}) as _LauncherLifecycleObserver<T>;
observer.launchOnDestroy = launchOnDestroy;
if (repeatOnStarted != null) {
observer.repeatOnStarted = repeatOnStarted;
}
if (repeatOnResumed != null) {
observer.repeatOnResumed = repeatOnResumed;
}
return value;
}