0

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));
  }
Codeopold
  • 45
  • 8

1 Answers1

2

Try navigating to your settings page like this, this way the screen underneath it won't die.

                  Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => SecondPage(),
                          ));
Yasine Romdhane
  • 566
  • 4
  • 13
  • First of all thanks for your quick response. The problem is that I don't use a NavBar. Instead I only use swipe gestures to switch between pages. So I think it's not possible to use ```Navigator.push()``` – Codeopold Oct 11 '21 at 18:49
  • I changed my page switching from PageView to Navigator.push. The method you recommended works. Thanks – Codeopold Oct 12 '21 at 13:57
  • Great, since it worked consider marking my answer as accepted. Happy coding :) – Yasine Romdhane Oct 12 '21 at 14:09
  • Yeah I noticed it too and was about to mark it :) Thanks again – Codeopold Oct 12 '21 at 14:21