I generally program in C++ and aware how the Sleep function work, but learning dart (for flutter) now i came across this delay function

void countSeconds(s) {
  for( var i = 1 ; i <= s; i++ ) {
      Future.delayed(Duration(seconds: i), () => print(i));
   }
}

It prints value of i after ith second, but shouldn't it print 1 after 1 sec, 2 after another 2 sec ( ie 3 ), 3 after another 3 secs (ie 6 sec) etc. How is it working?


Solution 1: Adelina

This will print 1 after 1s, 2 after another 2s, 3 after 6s.

 for( var i = 1 ; i <= 5; i++ ) {
      await Future.delayed(Duration(seconds: i), () => print(i));
   }

In asynchronous programming you need to await for futures to return result. Otherwise it will return everything immediately