Search code examples
flutterdarttimerdispose

timer doesn't dispose when I leave the page


I call my timer on initState every 10 seconds, but it doesn't dispose when I leave the page.

_timer = Timer.periodic(Duration(seconds: 10), (Timer t) => _onRefresh());
 _timer = Timer.periodic(
    Duration(seconds: 10), (Timer t) => _onRefreshIniciados());

I tried these two:

@override
  void dispose() {
    _timer?.cancel();
    _timer.cancel();
    super.dispose();
  }

The method dispose is called but it still keeps getting called every 10 seconds.


Solution

  • You are instantiating two instances of Timer, but only calling cancel on one of them.

    _timer = Timer.periodic(Duration(seconds: 10), (Timer t) => _onRefresh());
    // _timer references ^ this object
    
    _timer = Timer.periodic(
        Duration(seconds: 10), (Timer t) => _onRefreshIniciados());
    // _timer now references ^ object
    

    In other words, after your second instantiation, your _timer variable only 'remembers' the second Timer instance. So when you're calling cancel() you're only cancelling the second Timer, while the first one remains active.

    To fix this, declare two variables (_timer1, _timer2) and then cancel each of them:

    _timer1 = Timer.periodic(Duration(seconds: 10), (Timer t) => _onRefresh());
    _timer2 = Timer.periodic(
        Duration(seconds: 10), (Timer t) => _onRefreshIniciados());
    
    // ......
    
    @override
      void dispose() {
        _timer1.cancel();
        _timer2.cancel();
        super.dispose();
      }