Synchrounous way to check if Future completed

Viewed 671

Is there is a synchronous way to check if a Future has completed in Dart?

Cheers!

2 Answers

No.

There is deliberately no way to check synchronously whether a future has already completed.

You can obviously keep track yourself:

Foo result = null;
fooFuture.then((value) { result = value; });
...
/// later
if (result != null) ...

That still only works after the first microtask, because your callback won't get called any sooner than that.

You can use Completer class.

final completer = Completer();

myFuture
  .then(completer.complete)
  .catchError(completer.completeError);

if (completer.isCompleted) {
  // Future has completed
}
Related