'Flutter timer resets when switching pages with bottom navigation bar

I have a timer that continuously runs, I want the timer to keep going even after switching between screens. Right now when navigating and coming back it resets. Since navigating with bottom navigation bar I found it hard to find a solution. Let me know if there is more information needed to make the question better. Help would be appreciated.

 late double? workingHours = prefs.getDouble('workingHours');
  late double? workingMinutes = prefs.getDouble('workingMinutes');
  var time = Time();

  @override
  void initState() {
    super.initState();
    time = Time(
      hours: workingHours!,
      minutes: workingMinutes!,
      seconds: 0,
    );
    Timer.periodic(
      const Duration(seconds: 1),
      (timer) {
        if (mounted) {
          setState(
            () {
              if (time.seconds < 60) {
                time.seconds++;
              } else {
                if (time.minutes < 60) {
                  time.minutes++;
                } else {
                  time.minutes = 0;
                  time.hours++;
                }
                time.seconds = 0;
              }
            },
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: RichText(
        text: TextSpan(
          text: '${time.hours.toStringAsFixed(0)} hrs - ',
          style: const TextStyle(
              color: Colors.black, fontSize: 30, fontWeight: FontWeight.bold),
          children: <TextSpan>[
            TextSpan(
              text: '${time.minutes.toStringAsFixed(0)} mins',
              style: const TextStyle(
                color: Colors.black,
                fontSize: 30,
                fontWeight: FontWeight.bold,
              ),
            ),
            TextSpan(
              text: time.seconds.toStringAsFixed(0),
              style: const TextStyle(color: Colors.blue, fontSize: 20),
            )
          ],
        ),
      ),
    );
  }
}


Solution 1:[1]

A better solution is to store a "start-time" instead of having a timer that counts time for you. A periodic timer does not count time accurately: even though you set it to "repeat every 1 second" it would actually fire the event slightly later than 1 second every time, so the error accumulates over time, and your timer would become less and less accurate.

In your case, you can store a timestamp when the app first launches, and then have a periodic timer to refresh the UI to do a calculation, i.e. current time minus the time when the app first launched.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WSBT