Home > front end >  Dispose not working when used with Timer in Dart / Flutter
Dispose not working when used with Timer in Dart / Flutter

Time:10-31

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'.

CodePudding user response:

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

  • Related