Dispose not working when used with Timer in Dart / Flutter

Issue

How can I get it to work?

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

And this is what I have:

class _ListCell extends State<ListCell> {
  @override
  void initState() {
    super.initState();
    Timer timer = Timer.periodic(Duration(seconds: 1), (_) => ListCell());
  }

Constantly getting the error:

 Error: The getter 'timer' isn't defined for the class '_ListCell'.

Solution

You’re getting the error because the timer variable is defined out of the scope of the dispose method. This is because you defined the variable in the initState method.

Solution:

Move the definition of the timer variable outside the initState method like this:

class _ListCell extends State<ListCell> {
  Timer? timer;

  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(Duration(seconds: 1), (_) => ListCell());
  }
  
  ...

Since the timer variable is now nullable as it is of type Timer?, you need to use the null-check operator on it in the dispose method.

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

Checkout Dart’s Lexical Scope

Answered By – Victor Eronmosele

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published