Search code examples
dartdart-null-safety

Why doesn't the late Timer.periodic work in flutter & dart?


This timer does not work.
Why?
What is late doing?

import 'dart:async';

void main() => A();

class A {
  final a = 10;
  late final Timer timer = Timer.periodic(
    Duration(seconds: 1),
    (timer) {
      print(a);
    },
  );
}

Solution

  • late have multiple meanings in Dart but if used when declaring value of the variable right away, it means the variable are first assigned its value when you access the variable the first time.

    So your code are not doing anything since you, at no point, are trying to read the timer variable.

    You can read more about this in the official documentation: https://dart.dev/null-safety/understanding-null-safety#lazy-initialization