androidfluttertimerbackground-service

How to run clock timer in background on flutter?


I am trying to develop a timer app in Flutter that includes multiple countdown timers for different tasks. However, I'm facing an issue where if I start a timer and then press the back button, the timer stops. I want the timer to continue running until it is either paused or it reaches the end, even if the user navigates away from the app or the app is closed. I am also using SQLite to store all the timers. How can I achieve this functionality in Flutter?


Solution

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