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);
},
);
}
CodePudding user response:
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
CodePudding user response:
You are trying to do a Lazy initialization for the timer
, but there is just a little point you are missing that causes the current behavior.
As the official docs states:
When you do this, the initializer becomes lazy. Instead of running it as soon as the instance is constructed, it is deferred and run lazily the first time the field is accessed.
So by creating a new object of class A
by calling it is constructor, this will not initialize the timer
, it would be initialized once it is accessed, and that is the meaning of Lazy initialization
.
So if we accessed the timer
property inside the constructed object, the intended behavior will occur and the timer callback
would run as you want.
Try this one:
void main(){
final aObject = A();
print(aObject.timer);
}
I have created the example in DartPad to let you easily test and play around with it, access it via this link.
CodePudding user response:
late modifier means “enforce this variable’s constraints at runtime instead of at compile time”.
You can check lazy-initialization.
When you do this, the initializer becomes lazy. Instead of running it as soon as the instance is constructed, it is deferred and run lazily the first time the field is accessed. In other words, it works exactly like an initializer on a top-level variable or static field. This can be handy when the initialization expression is costly and may not be needed.
Find more late keyword with declaration
And doing void main() => A();
just creating an instace of A.
If you like to run timer, do it like
void main() {
final a = A();
a.timer;
}