使用 M3 Dart,最好只使用您自己的标志。
future.whenComplete() {
tweenCompleted = true;
}
Run Code Online (Sandbox Code Playgroud)
Dart 是一种单线程语言,因此这里没有竞争条件。请注意,[action] 函数在此 future 完成时被调用,无论是使用值还是错误。
@Cutch解决方案的替代方案是Future将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
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法更加灵活,因为您既可以异步等待完成,又可以检查 future 是否同步完成。
使用 Future 的扩展并以 Hugo Passos 的答案为基础:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1206 次 |
| 最近记录: |