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

Currently I´m using this one in Dart as proposed by chatgpt 😉 but is there a better way to wait for not null? (PS: this is pure dart backend code, so Flutter Futurebuilder is not possible)

  String? command;

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

Thanks!

You can change command into a Completer from dart:async:

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

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

And when you want to assign a value to the completer you call:

command.complete(yourValue);

instead of doing

command = yourValue;

Leave a Comment