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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With