如何使用 ref.read 等待 AsyncData?

问题描述 投票:0回答:1

我正在使用 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>>
的事情?

flutter dart riverpod
1个回答
0
投票

最后,我创建了这个扩展:

/// 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);
© www.soinside.com 2019 - 2024. All rights reserved.