有没有更优雅的方式在异步方法中等待 Dart 中的 !=null?

Is there a more elegant way to wait for !=null in Dart in async methods?

提问人:Defarine 提问时间:11/16/2023 更新时间:11/16/2023 访问量:32

问:

目前我正在 chatgpt 建议的 Dart 中使用这个;但是有没有更好的方法来等待 Not null?(PS:这是纯 dart 后端代码,所以 Flutter Futurebuilder 是不可能的)

  String? command;

  Stream<({Message message})> detect(List<Message> messages) async* {
    while (command == null) {
      await Future.delayed(const Duration(milliseconds: 100));
    }
  ...

谢谢!

dart async-await

评论


答:

4赞 Valentin Vignal 11/16/2023 #1

你可以从 dart:async 更改为 Completercommand

final Completer<String> command = Completer<String>();

Stream<({Message message})> detect(List<Message> messages) async* {
  await command.future;
  // ...
}

当您想为完成器赋值时,请调用:

command.complete(yourValue);

而不是做

command = yourValue;