如何在Flutter的后台运行时钟计时器? [英] How to run clock timer in background on flutter?

查看:442
本文介绍了如何在Flutter的后台运行时钟计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个计时器应用程序,该应用程序具有用于不同任务的多个倒数计时器.我面临的问题是,如果我启动一个计时器,然后按返回"按钮,计时器将停止.所以我想让计时器一直运行到暂停或计时器结束并提醒用户或应用程序销毁.请帮助我如何使用Flutter做到这一点?我也使用sql-lite存储所有计时器.

I am try to create a timer app which have multiple countdown timer for different task. Issue, i am facing is that, if i start one timer, and press back button, timer stops. So i want, that timer to run till either it is being paused or timer ends and alerts the user or app is destroyed.Help me how can i do this using Flutter? Also i using sql-lite to store all timers.

推荐答案

啊,后台任务! 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.youtube.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.

这篇关于如何在Flutter的后台运行时钟计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆