Completer是一个用于创建 Future 的辅助类,而 Future 是一个Type.
所有异步函数都返回 Future,但是使用 Completer 可以创建也返回 Future 的同步函数。您也可以将同步功能与then等链接起来。
Completer 对象是一种方式进程,它不可重启。它完成工作并停止。
Future<MyObject> myMethod() {
final completer = Completer();
completer.complete(MyObject());
return completer.future;
}
Run Code Online (Sandbox Code Playgroud)
更新:
举个例子,在我的一个项目中,我必须获取网络图像的分辨率信息。要做到这一点,你需要这样的东西:https : //stackoverflow.com/a/44683714/10380182
在那里,如您所见,在获取图像后,我们会执行解析过程,即使它不是异步过程,也可能需要一些时间。为了消除这种阻塞,我们只需使用Completer.
我们需要的信息也存在于回调中,所以Completer在那里使用会更干净。然后,我们通过FutureBuilder. 您可以采用不同的方法,但这是非常方便的处理方式。
ACompleter是用于Future从头开始创建的类。因此,除非您真的是Future从头开始创建,否则您可能不应该使用Completer.
您可以Completer使用Future的构造函数在不使用 a的情况下创建 Future :
final myFuture = Future(() {
final result = doSomethingThatTakesTime();
return result;
});
Run Code Online (Sandbox Code Playgroud)
使用Future.then()是另一种获得 a 的方法Future:
Future<bool> fileContainsBear(String path) {
return File(path).readAsString().then((contents) {
return contents.contains('bear');
});
}
Run Code Online (Sandbox Code Playgroud)
任何async/await方法都返回一个 Future:
Future<bool> fileContainsBear(String path) async {
var contents = await File(path).readAsString();
return contents.contains('bear');
}
Run Code Online (Sandbox Code Playgroud)
以上方法都推荐使用Completer:
// This is harder to read.
Future<bool> fileContainsBear(String path) {
var completer = Completer<bool>();
File(path).readAsString().then((contents) {
completer.complete(contents.contains('bear'));
});
return completer.future;
}
Run Code Online (Sandbox Code Playgroud)
但如果你真的需要使用 Completer,方法是这样的:
Completer.future.下面是一个例子:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
此答案中的代码来自文档和Effective Dart 指南。
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |