我正在使用 riverpod 并且我想在回调中读取
Provider<AsyncValue>
(例如按钮)。
我想确保读取的值不是
AsyncLoading
。
onPressed: () {
final AsyncValue<T> value = ref.read(myProvider); // I want to make sure it is not AsyncLoading
}
Provider<AsyncValue<T>> myProvider
是 NOT FutureProvider
或 StreamProvider
所以我不能使用
final T value = await ref.read(myProvider.future); // I cannot do it. myProvider is not a FutureProvider or a StreamProvider
如何做类似于
await ref.read(myProvider.future)
但对于通用 Provider<AsyncValue<T>>
的事情?
最后,我创建了这个扩展:
/// An extension on [WidgetRef] with helpful methods to read an [AsyncValue].
extension AwaitAsyncValue on WidgetRef {
/// Waits for the [AsyncValue] to be resolved and returns the value.
Future<T> readAsync<T>(ProviderBase<AsyncValue<T>> provider) {
final completer = Completer<T>();
final subscription = listenManual(
provider,
(previous, next) {
next.when(
data: completer.complete,
loading: () {},
error: completer.completeError,
);
},
fireImmediately: true,
);
completer.future.then((_) => subscription.close(), onError: (_) => subscription.close());
return completer.future;
}
}
我可以这样使用它:
final T value = await ref.readAsync(myProvider);