Persistent stopwatch that can be paused/unpaused in flutter

Viewed 22

My flutter app allows users to time how long they have been working for. I'm using the package stop_watch_timer.

Everything works fine except when the app gets killed in the background, because then I lose the timer value and it goes back to 0. As users are likely to start the timer then put their phone away and work for a while, the app getting killed is a very likely scenario and I need to make sure that this never happens. Another feature that I need in the app is for users to be able to pause and unpause the timer whenever they want.

Here are the solutions I have come up with so far and their problems:

  • Solution 1: Store the start DateTime on the phone using shared_preferences and calculate the current timer value when app is reopened by simply calculating the duration between start time and DateTime.now(). But then I realised that this does not work if the user had paused and unpaused the timer at some point.

  • Solution 2: Store the current timer value as a RestorableInt. This works if the timer is on pause when the app gets killed, but does not work if the timer is meant to be running when the app dies.

Any suggestions or ideas??

1 Answers

You should store something like this:

[
{"start":1664027960},
{"pause":1664027975},
{"unpause":1664027979},
{"pause":1664028061},
{"unpause":1664028065},
]

Everytime a user hits the pause button you add the time to the list and store it in the shared_prefs or in a json file. Same for unpausing.

You can then calculate the total ellapsed time.

Related