How to run clock timer in background on flutter?

被刻印的时光 ゝ 提交于 2020-05-28 04:41:26

问题


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.


回答1:


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

What does single-threaded mean?

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.

I recommend this article and video on single-threaded stuff:

https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a

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

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).

This article (conveniently enough) covers timers in Isolates:

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

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



来源:https://stackoverflow.com/questions/59480124/how-to-run-clock-timer-in-background-on-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!