withLifecycleAndDataEffect<T extends Object> method
T
withLifecycleAndDataEffect<T extends Object>({})
从当前的Context
中获取Lifecycle
使用 并且data 同属于 key的一部分
- 如果使用
factory
,factory2
则必须保证多次调用时返回同一值 否则将会视为新建
Implementation
T withLifecycleAndDataEffect<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,
Object? key,
}) {
assert(data != null || factory != null || factory2 != null,
'data and factory and factory2 cannot be null at the same time');
data ??= factory?.call();
final lifecycle = Lifecycle.of(this);
data ??= factory2?.call(lifecycle);
if (data == null) {
throw 'data and factory and factory2 cannot be null at the same time';
}
final ctx = this;
final d = data;
final cache = lifecycle.extData
.putIfAbsent<Map<BuildContext, Map<Object, _DLauncherObserver>>>(
key: _withLifecycleAndDataKey, ifAbsent: () => WeakHashMap());
final cache2 = cache.putIfAbsent(ctx, () {
final result = HashMap<Object, _DLauncherObserver>();
lifecycle.addLifecycleObserver(MapAutoClearObserver(result));
return result;
});
final observer =
cache2.putIfAbsent(key == null ? d : _LifecycleAndDataKey(d, key), () {
final observer = _DLauncherObserver<T>._(ctx, d);
observer.launchOnFirstCreate = launchOnFirstCreate;
observer.launchOnFirstStart = launchOnFirstStart;
observer.launchOnFirstResume = launchOnFirstResume;
observer.launchOnDestroy = launchOnDestroy;
if (repeatOnStarted != null) {
observer.repeatOnStarted = repeatOnStarted;
}
if (repeatOnResumed != null) {
observer.repeatOnResumed = repeatOnResumed;
}
lifecycle.addObserver(observer);
return observer;
}) as _DLauncherObserver<T>;
if (repeatOnStarted != null) {
observer.repeatOnStarted = repeatOnStarted;
}
if (repeatOnResumed != null) {
observer.repeatOnResumed = repeatOnResumed;
}
if (launchOnDestroy != null) {
observer.launchOnDestroy = launchOnDestroy;
}
return data;
}