且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Flutter的后台运行时钟计时器?

更新时间:2023-11-17 16:35:58

啊,后台任务! Dart(Flutter使用的语言)是单线程.

Ah, background tasks! Dart (the language Flutter uses) is single-threaded.

单线程语言(例如Dart)具有称为事件循环的东西.这意味着Dart逐行运行代码(除非您使用Futures,但在这种情况下将无济于事).它注册诸如按钮点击之类的事件,并等待用户按下它们,等等.

Single-threaded languages such as Dart have something called an event loop. That means that Dart runs code line by line (unless you use Futures but that won't help you in this case). It registers events like button taps and waits for users to press them, etc.

我推荐这篇文章和有关单线程内容的视频:

https://medium.com/dartlang/dart异步编程隔离和事件循环bffc3e296a6a

https://www.***.com/watch?v=vl_AaCgudcY& feature = emb_logo

无论如何,解决此问题的方法(如上文文章和视频所述)是隔离.在Dart中创建隔离时,它会旋转另一个线程来执行繁重的任务,或者只是在应用程序可能或可能不处于焦点时执行某些操作.这样,主线程可以加载UI之类的东西,而在另一个线程中,它可以照顾您放入其中的其他东西,因此,可以提高应用程序的性能.

Anyways, the way to combat this (as mentioned in the article and video above) is Isolates. When you create an Isolate in Dart, it spins up another thread to do heavy tasks or just something while the app may or may not be in focus. That way, the main thread can load things like UI while in another thread, it takes care of the other stuff you put in it, therefore, increasing the performance of your app.

它与您的问题有什么关系?

How does it relate to your question?

您可以使用隔离"在应用程序后台(无论是否打开)执行任务.

You can use Isolates to execute tasks in the background of your app (open or not).

本文(足够方便)介绍了隔离中的计时器:

https://codingwithjoe.com/dart-fundamentals-isolates/

基本上,它在隔离物中使用Timer.periodic来执行对于您的场景而言完美的任务.

Essentially it uses Timer.periodic inside an isolate to execute tasks which is perfect for your scenario.