0

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,
            )));
  }
}
Jelle Huevo
  • 3
  • 1
  • 3

4 Answers4

0

You need to @override before initState and inside it you need to call super.initState()

ammar
  • 121
  • 8
0

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--;
});
Mohamad Bastin
  • 309
  • 2
  • 6
0

There are errors in your code

add super.initState(); in init state 

seconde your call back function should looks like setState((){ _counter--;

  });
0

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,
            )));
  }
}
nagendra nag
  • 1,142
  • 2
  • 15