'LateInitializationError: Field '_timer@137128430' has not been initialized in flutter Null safe version
I'm beginner for the flutter , I have added flowing code and flutter suggested to add late, I added late Timer _timer;
after it showed me the following error
LateInitializationError: Field '_timer@137128430' has not been initialized.
any solution for this? Thanks
code here
late Timer _timer;
int _start = 60;
//start timer
void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) {
if (_start == 0) {
setState(() {
timer.cancel();
});
} else {
setState(() {
_start--;
});
}
},
);
}
@override
void initState() {
super.initState();
startTimer();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
Solution 1:[1]
Use Timer? _timer;
instead of late Timer _timer;
Solution 2:[2]
Please call startTimer() before super.initState() in the initState. Like below
@override
void initState() {
startTimer();
super.initState();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pranav |
Solution 2 | core114 |