Make a while loop, loop for 1 second in Dart/Flutter

Viewed 6775

I am trying to make a while loop loop a statement exactly for one second after which it stops. I have tried this in DartPad, but it crashes the browser window.

void main(){
  
  var count = 0.0;
  bool flag = true;
  
  Future.delayed(Duration(seconds: 1), (){
    flag = false;
  });
  
  while (flag){
    count++;
  }
  
  print(count);
  
}

Am I doing something wrong?

1 Answers

I like how you are trying to figure Futures out. I was exactly where you were before I understood this stuff. It's kind of like threads, but quite different in some ways.

The Dart code that you wrote is single threaded. By writing Future.delayed, you did not start a job. Its execution won't happen unless you let go of the thread by returning from this main function.

Main does not have to return if it is marked with async.

Two actions have to run "concurrently" to be able to interact with each other like you are trying to do. The way to do it is to call Future.wait to get a future that depends on the two futures. Edit: Both of these actions have to let go of execution at every step so that the other can get control of the single thread. So, if you have a loop, you have to have some kind of await call in it to yield execution to other actions.

Here's a modified version of your code that counts up to about 215 for me:

Future main() async {
  
  var count = 0.0;
  bool flag = true;
  
  var futureThatStopsIt = Future.delayed(Duration(seconds: 1), (){
    flag = false;
  });
  
  var futureWithTheLoop = () async {
    while (flag){
      count++;
      print("going on: $count");
      await Future.delayed(Duration(seconds: 0));
    }
  }();

  await Future.wait([futureThatStopsIt, futureWithTheLoop]);
  
  print(count);
  
}
Related