In my flutter app there is a timer and a settings page. When the timer is running and I switch to the setting page (by using PageView), the timer gets reset or there is an error (Unhandled Exception: setState() called after dispose()) This happens because I use setState to decrease the time.
    if (!mounted) return;
    setState(() {
      final seconds = duration.inSeconds - 1;
      if (seconds < 0) {
        isWork = !isWork;
        reset(autostartSession);
      } else {
        duration = Duration(seconds: seconds);
      }
    });
}
The timer still keeps running if I turn off the screen. Can someone tell me how I can switch pages without resetting the timer or getting an error?
BTW I created the timer myself and didn't use a package.
Widget buildTimer() {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return Text('$minutes:$seconds', style: const TextStyle(fontSize: 80));
  }