'Timer not cancelling flutter

I needed a single instance of a timer to run on my app such that i can cancel and reinitialise it when needed. However, the timer doesn't cancel after calling the .cancel() operation. It only work if i call it from the default constructor but i want a global timer i can cancel anytime;

Timer timer;

  timer = Timer.periodic(Duration(seconds: 10), (Timer t) async {
         //cancelling timer only works here e.g (t.cancel)
  print("loop operation");
        });

timer.cancel(); // calling this method outside the constructor don't work.


Solution 1:[1]

I had a similar problem. This happened after I made the callback function async.

I think the solution will differ from problem to problem depending on why your callback is async.

This is not a solution, but rather a hint to get you closer to the solution.

Solution 2:[2]

Timer timer;

Timer.periodic(Duration(seconds: 10), (Timer t) async {
            timer = t;
            print("loop operation");
        });


//inside a button callback
timer??.cancel(); // perform null check as well before cancelling.

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 Lebohang Mbele
Solution 2 Doc