Before 'm3' you could check if a Future was completed with 'completer.future.isComplete' this seems to be gone. Is there a replacement? or do I need to save it myself then (it seems inside the _CompleterImpl there is still a field '_isComplete' but its not exposed
An alternative to @Cutch's solution is to wrap the Future
in a Completer
:
Completer<T> wrapInCompleter<T>(Future<T> future) {
final completer = Completer<T>();
future.then(completer.complete).catchError(completer.completeError);
return completer;
}
Future<void> main() async {
final completer = wrapInCompleter(asyncComputation());
if (completer.isCompleted) {
final result = await completer.future;
// do your stuff
}
}
This approach is more resourceful since you can both await for the completion asynchronously and check whether the future is completed synchronously.
With M3 Dart, it's best to just use your own flag.
future.whenComplete(() {
tweenCompleted = true;
});
Dart is a single threaded language so there is no race condition here. Note that the [action] function is called when this future completes, whether it does so with a value or with an error.
Using an extension on Future and building on Hugo Passos' answer:
extension FutureExtension<T> on Future<T> {
/// Checks if the future has returned a value, using a Completer.
bool isCompleted() {
final completer = Completer<T>();
then(completer.complete).catchError(completer.completeError);
return completer.isCompleted;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With