dart 如何等待值通知器不为“null”?

2cmtqfgy  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(80)

我有一个全局ValueNotifer<MyType?> myNotifier,它最初保存一个null值。在一些API请求之后,它将异步更新,并将具有一个非空值MyType
我有一个方法myMethod,它需要等待myNotifier被初始化,然后才能执行某些操作。

Future<void> myMethod() async {
  // How to wait for `myNotifier` to have a non-null value here?
  assert(myNotifier.value != null, 'This requires myNotifier.value to be non-null');

  // Perform some action with a non-null `myNotifier.value`.
}

字符串
如何等待myNotifier.value为非空?

mzmfm0qo

mzmfm0qo1#

最后,我想出了这个解决方案:

extension ValueNotifierExtension<T> on ValueNotifier<T?> {
  Future<T> waitForNonNullValue() async {
    if (value != null) return value!;
    final completer = Completer<T>();
    void listener() {
      if (value != null) {
        completer.complete(value);
      }
    }

    addListener(listener);
    final result = await completer.future;
    removeListener(listener);
    return result;
  }
}

字符串
这让我可以做到:

Future<void> myMethod() async {
  final value = await myNotifier.waitForNonNullValue();
  assert(value != null && myNotifier.value != null, 'This requires myNotifier.value to be non-null');

  // Perform some action with a non-null `myNotifier.value`.
}

相关问题