I'm trying to create a simple widget which counts down from 10 upon getting built. I expected this to start counting down but it remains stuck on 10. Could anyone see what is going wrong here?
class GameTimer extends StatefulWidget {
const GameTimer({
Key? key,
}) : super(key: key);
@override
State<GameTimer> createState() => _GameTimerState();
}
class _GameTimerState extends State<GameTimer> {
initState() {
_startTimer();
}
int _counter = 10;
late Timer _timer;
void _startTimer() {
_counter = 10;
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState() {
_counter--;
}
});
}
@override
Widget build(BuildContext context) {
return SizedBox(
child: Text('$_counter',
style: TextStyle(
fontSize: 48,
fontWeight: FontWeight.bold,
)));
}
}
CodePudding user response:
You need to @override before initState and inside it you need to call super.initState()
CodePudding user response:
First of all your initState isnt overriding the super method. so it should be like this:
@override
initState() {
_startTimer();
super.initState();
}
Second, in your _startTimer you are declaring a new function called setState. you missed a couple of parentheses:
setState(() {
_counter--;
});
CodePudding user response:
There are errors in your code
add super.initState(); in init state
seconde your call back function should looks like setState((){ _counter--;
});
CodePudding user response:
You are almost there !!!!!!
You have missed wrapping the setState callback in parentheses.
Updated code:
class GameTimer extends StatefulWidget {
const GameTimer({
Key? key,
}) : super(key: key);
@override
State<GameTimer> createState() => _GameTimerState();
}
class _GameTimerState extends State<GameTimer> {
initState() {
_startTimer();
}
int _counter = 10;
late Timer _timer;
void _startTimer() {
_counter = 10;
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
_counter--;
});
});
}
@override
Widget build(BuildContext context) {
return SizedBox(
child: Text('$_counter',
style: TextStyle(
fontSize: 48,
fontWeight: FontWeight.bold,
)));
}
}
