Dan*_*ton 6 dart flutter riverpod
我希望能够创建 StreamProvider.autoDispose 并在 StateNotifier 内监听它。
\n这样,当 StateNotifierProvider.autoDispose 被释放时,StreamProvider 也将被释放。否则它会保持打开状态,这是我不想要的。
\n但是,StateNotifierProvider 只能访问 Ref,而不能访问 WidgetRef。\n因此我无法使用 .autoDispose 创建 StreamProvider,或者收到此错误:
\n参数类型“AutoDisposeStreamProvider”无法分配给参数类型“AlwaysAliveProviderListenable<AsyncValue>”。
\nfinal filterList =\n StateNotifierProvider.autoDispose<FilteredListNofifier, List<ServerItem>>(\n (ref) {\n return FilteredListNofifier(ref);\n});\n\nclass FilteredListNofifier extends StateNotifier<List<ServerItem>> {\n FilteredListNofifier(Ref ref) : super(<ServerItem>[]) {\n ref.listen(filterListStream, (previous, AsyncValue<List<ServerItem>> next) {\n if (next.value != null) {\n state = next.value!;\n }\n });\n }\n}\n\nfinal filterListStream = StreamProvider.autoDispose<List<ServerItem>>((ref) async* {\n yield [];\n});\nRun Code Online (Sandbox Code Playgroud)\n
watch你可以像这样使用:
final filterList =
StateNotifierProvider.autoDispose<FilteredListNofifier, List<ServerItem>>(
(ref) {
final a = ref.watch(filterListStream);
return FilteredListNofifier(a);
});
class FilteredListNofifier extends StateNotifier<List<ServerItem>> {
FilteredListNofifier(AsyncValue<List<ServerItem>> l) : super(<ServerItem>[]) {
if (l.asData != null) {
state = l.asData!.value;
}
}
}
final filterListStream = StreamProvider.autoDispose<List<ServerItem>>((ref) async* {
yield [];
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4779 次 |
| 最近记录: |