Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: Unexpected text 'late'

Tags:

flutter

dart

Going through this tutorial on Riverpod and using this code gives an error Unexpected text 'late'

class Clock extends StateNotifier<DateTime> {

  Clock() : super(DateTime.now()) {
    _timer = Timer.periodic(Duration(seconds: 1), (_) {
      state = DateTime.now();
    });
  }

  late final Timer _timer;

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

My code is exactly the same as found on the linked website. This error looks strange as I haven't found anything on google or stackoverflow similar to this.

like image 450
gegobyte Avatar asked Apr 15 '21 18:04

gegobyte


People also ask

What does Late mean in darts?

In Dart, we use the late keyword to declare variables that will be initialized later. These are called non-nullable variables as they are initialized after the declaration. Hence, we use the late keyword.

What is late keyword?

late keyword enforces a variable's constraints at runtime instead of at compile time and since the variable is not definitely initialized, every time it is read, a runtime check is inserted to make sure it has been assigned a value.

Why late is used in Flutter?

late modifier means “enforce this variable's constraints at runtime instead of at compile time”. It's almost like the word “late” describes when it enforces the variable's guarantees. When you do this, the initializer becomes lazy.


1 Answers

late is for projects converted to null safety using min dart sdk 2.12. It tells the compiler that it's null now but will be initialized later on. You can either omit the late keyword in that case or change the min sdk in your pubspec.yaml to 2.12.

like image 169
Loren.A Avatar answered Oct 23 '22 12:10

Loren.A