Search code examples
flutterdartflutter-animation

How to cancel sub Timer inside nested Timer?


I am having a problem with cancelling one nested Timer. These are the code example I have:

import 'dart:async';

void main() async{
 final timer =
    Timer(const Duration(seconds: 1), () {
      print('Timer 1');
      Timer(const Duration(seconds:1),(){
        print('Timer 2');
      });
    });
  
  Timer(Duration(milliseconds: 1500),(){
    timer.cancel();    
        print('timer cancelled');
      });
}

The result:

Timer 1
timer cancelled
Timer 2

What I am expected:

Timer 1
timer cancelled

A little about my usecase, I want to create a quite complex animation and I use the nested Timer to set the specific timing of the animation.

The problem occur when the user move forward and instantinously move backward, the animation that still inside the Timer will still run 'forward' (because it's still deep inside the nested timer) even though the 'reverse' animation should be the only one that run.

That is why I am only expecting Timer 1 to be printed instead of both Timer 1 and 2 even though the Timer has been cancelled

Any feedback or input would be appreciated.

What I am expected:

Timer 1
timer cancelled

Solution

  • I think this will print your expected result. Just keep a reference to the second Timer. You can reuse the existing timer variable since after the first Timer fires to create the second Timer, you no longer need a reference to the first one.

    import 'dart:async';
    
    void main(List<String> args) {
      Timer? timer = null;
        timer = Timer(const Duration(seconds: 1), () {
          print('Timer 1');
          timer = Timer(const Duration(seconds: 1),(){
            print('Timer 2');
          });
        });
      
      Timer(Duration(milliseconds: 1500),(){
        timer?.cancel();    
            print('timer cancelled');
          });
    }