Flutter中Completer和Isolates的解释和区别

Explanation and difference between Completer and Isolates in Flutter

我需要在我的应用程序上 return 一个 Future,因为我认为我的功能需要太多时间才能完成。

所以我得到了两个可能的答案:使用 Completer or an Isolate.

是什么让我选择其中之一? 我可以将 Completer 放在任何我想要的地方并相信它会正常工作吗?

这是如何运作的?比如.. Flutter 必须以 60fps 的速度在屏幕上绘制,对吧?那么,它会在 canvas 上绘制之后和下一次绘制之前计算这些东西吗?我很好奇,因为 Flutter 不是多线程的(但似乎 isolates 可以做到这一点)。所以我很困惑,不知道如何编写可信赖的代码。

另外,有没有理由不使用 Completer?就像,我认为我的代码花费了太多时间,但也许不是..是否有理由检查完成所需的时间,如果它低于阈值我不应该使用它?

提前致谢。

返回 Future(完成者)可确保您的长函数的 activity 与您的原始线程位于 同一线程 中。 Isolate 自动处于具有自己的事件循环的不同的无共享线程中,并且必须使用消息传递来访问或 return 值。

这篇文章对我理解这个异步的东西帮助很大:https://www.didierboelens.com/2019/01/futures---isolates---event-loop/

除了代码解释外,我认为结论回答了我的问题:

Therefore, here are some hints you should systematically take into consideration in your developments:

If pieces of codes MAY NOT be interrupted, use a normal synchronous process (one method or multiple methods that call each other);

If pieces of codes could run independently WITHOUT impacting the fluidity of the application, consider using the Event Loop via the use of Futures;

If heavy processing might take some time to complete and could potentially impact the fluidity of the application, consider using Isolates.