auto increment in every 500 miliseconds flutter

Viewed 549

I am trying to increment _counter state in every 500 milliseconds for 100 times.

So I tried this:

int _counter = 0;

  _incrementCounter() {
    setState(() {
      for (var i = 0; i < 100; i++) { //Loop 100 times
        Future.delayed(const Duration(milliseconds: 500), () { // Delay 500 miliseconds
          _counter++; //Increment Counter
        });
      }
    });
  }

But its increment 0 to 100 in 1 click.

What I am doing wrong?

3 Answers

You need to use the setState() inside your Future.delayed() method. It will look like this:

    int _counter = 0;

    _incrementCounter() async {
      
        for (var i = 0; i < 100; i++) { //Loop 100 times
          await Future.delayed(const Duration(milliseconds: 500), () { // Delay 500 milliseconds
           setState(() {
            _counter++; //Increment Counter
             }
          });
        
      });
    }

Using just the future

int _counter = 0;
await Future.doWhile(() async {
  await Future.delayed(const Duration(milliseconds: 500));
  _counter++;
  return _counter!=100;
});

Another solution would be using periodic Timer.

int counter = 0;
Timer? timer;

timer = Timer.periodic(Duration(milliseconds: 500), ()  {
  counter ++;

  if (counter == 100) {
    timer!.cancel();
  }
});
Related