Skip to content Skip to sidebar Skip to footer

How To Run Clock Timer In Background On Flutter?

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 wa

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

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

Solution 2:

Isolates won't solve the problem. even isolates gets paused by the OS when the app is in the background. I have tried it (in Android10 timer runs for about 100 seconds before it gets paused by the system).

for your problem Android_Alarm_Manager package seems to be the solution. but it only supports android. no ios support yet

Solution 3:

I had a similar problem. The isolate won't solve it since the isolates life cycle is also linked to the main isolate(ui thread). I sort of created a workaround,i.e I used the dateTime property,so if the user chooses 30 minutes,the final Date time becomes Date time.now(Duration (minutes:30));. And a timer periodic function which runs every minute and finds the difference between the final date time and the datetime.now() so even if the os kills ur app while in the background application tray when u reopen the app,the time automatically updates to the change. I also used flutter notification package to alert the user when the timer value becomes zero

Post a Comment for "How To Run Clock Timer In Background On Flutter?"