本文介绍了Flutter Future vs Completer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Future Completer 之间有什么区别?

我都不在寻找任何文档部分,而是希望看到一个示例,显示两者之间的真正区别.

I am not looking for documentation part on either, instead I would like to see an example showing the real difference between the two.

推荐答案

Completer 是用于创建Future的帮助类,而Future是 Type .

Completer is a helper class for creating Future whereas Future is a Type.

所有异步函数都返回Future,但是使用Completer可以创建也返回Future的同步函数.您也可以将同步功能与 then

All asynchronous functions return Future, but with Completer it is possible to create synchronous function that returns Future as well. Also you can chain that synch functions with then etc.

Completer对象是一种处理方法,它无法重新启动.它会完成工作并停止.

Completer object is one way process, it's not restartable. It does the job and stops.

Future<MyObject> myMethod() {
  final completer = Completer();
  completer.complete(MyObject());
  return completer.future;
}

更新:

举个例子,在我的一个项目中,我必须获取网络图像的分辨率信息.为此,您需要这样的事情: https://stackoverflow.com/a/44683714/10380182

To give an example, in one of my projects I had to get the resolution info of network images. To do that, you need something like this:https://stackoverflow.com/a/44683714/10380182

如您所见,在其中,获取图像后,我们执行了一个解析过程,即使它不是一个异步过程,也可能会花费一些时间.要消除这种阻塞,我们只需使用 Completer .

In there, as you see, after getting the image we do a resolve process which may take time even though it's not an async process. To eliminate that blocking we simply use Completer.

我们所需的信息也存在于回调中,因此在其中使用 Completer 会更干净.然后,我们通过 FutureBuilder 使用它.您可以采取不同的方法,但这是一种非常方便的处理方式.

Also the info we need exists inside a callback, so it will be cleaner to use Completer in there. Then, we use it via FutureBuilder. You can approach different but this is very convenient way to handle.

这篇关于Flutter Future vs Completer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 22:21