Flutter - Timer pauses unintentionally

1,387

Solution 1

I had issues with this as well. Things working correctly when running on the Simulator is fools gold. The Timer won't run in the background like you want it to unless you do specific work to keep it running. Here is the official page from Flutter on doing work in the background: https://flutter.dev/docs/development/packages-and-plugins/background-processes

Solution 2

I'll suggest implementing didChangeAppLifecycleState method of the WidgetsBindingObserver and detect when the app goes to the background and when it's back in the foreground. At the point where the app goes into the background, you save the current time e.g (onPauseTime) (you can use SharedPreferences here) and the Duration left on the timer (timerDurationLeft).

When the app is back in the foreground you check if the timer was running before the app entered the background state, if it was, you then check the current time e.g (onResumeTime) and calculate the time difference in seconds (onResumeTime - onPauseTime), using the time difference and the timerDurationLeft you can calculate how much time the timer has left to run and you start/resume the timer from that point or end/set the timer to 0:00 if time has already passed.

P:S Using a background service would be the way to go if you intend to perform some actions in the middle, like set notifications at some point where the timer is almost complete.

Share:
1,387
Chris
Author by

Chris

Updated on December 13, 2022

Comments

  • Chris
    Chris over 1 year

    I have implemented a Timer as detailed in the article below, so that the timer will keep running when i change tabs. How to implement persistent stopwatch in Flutter?

    I have an issue where the Timer "loses" or pauses time, only when not plugged into my computer. When i plug it into my computer, no issues, the emulator runs fine too. I test the flutter timer against a timer on my computer or phone, and after 5mins, they match. But when my phone (Galaxy S9) isn't plugged in, after 5mins of real time, the flutter timer might only be up to 2mins, when i go back into the app the timer is running but the timer wont be what it should be. It doesn't crash or reset, its counting when i get back into the app. I'm finding it hard to debug as when I plug the phone into my computer it seems to work fine! Any ideas?

  • Chris
    Chris over 4 years
    Ok thanks! Did you get yours working? I'll give it a go.
  • Eric Duffett
    Eric Duffett over 4 years
    I hadn't found this article when I built out my app so I I cheated. I built a meditation app and and I wanted to have the ability to do an unguided timed meditation. The way I got the timer to continue to countdown after my user locked the screen turn on permissions for background audio allow audio and play a silent audio track to keep the timer running.