0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

If I do that, I get this: Error: Field 'timer' should be initialized because its type 'Timer' doesn't allow null.
Use Timer? timer;. I have edited my answer.
Perfecto, thank you so much!
PS: what would be the difference between timer?.cancel and timer!.cancel?
Oh. I meant to write timer?.cancel. The difference is that timer?.cancel() means that the cancel() method will only run if timer is not null while timer!.cancel() means the cancel() method will run regardless so this is to be used when you're absolutely sure the variable is not null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.