Flutter 只知道 Future 还不够,你还需要 Completer
博客原文:Flutter 只知道 Future 还不够,你还需要 Completer
Completer
是创建 Future
的一种方式,它内部创建一个 Future
,并允许你在一段时间后主动完成它。一般如果你的异步操作是带回调的不能即时返回结果的类型,你需要用到 Completer
。
大多数时候,创建 Future
最简单的方式是直接通过其构造函数,去捕获一个异步计算的结果:
new Future(() { doSomething(); return result; });
或者是,用 future.then
来处理一连串的异步操作:
Future doStuff(){
return someAsyncOperation().then((result) {
return someOtherAsyncOperation(result);
});
}
但是如果你的计算操作是带 回调方法
的,上面的就不能用了。你需要使用 Completer
来创建:
class AsyncOperation {
Completer _completer = new Completer();
Future<T> doOperation() {
_startOperation();
return _completer.future; // Send future object back to client.
}
// Something calls this when the value is ready.
void _finishOperation(T result) {
_completer.complete(result);
}
// If something goes wrong, call this.
void _errorHappened(error) {
_completer.completeError(error);
}
}
使用 Completer
,你只需要这三步:
- 创建
Completer
- 把
Completer.future
分发出去 - 调用
completer.complete
或者completer.completeError
var completer = new Completer();
handOut(completer.future);
later: {
completer.complete('completion value');
}
一般使用 Completer()
构造的对象是 _AsyncCompleter
的实例,它的 complete
方法是异步的,这意味着 future
里注册的回调不会立刻执行,而是会延迟到下一个 microtask
。
如果你有特殊的需求要求同步完成,需要使用 Completer.sync
方法进行构造,它拿到的是 _SyncCompleter
对象实例。
转载自:https://juejin.cn/post/6896352801082114055