Async Dart function is not working properly

Viewed 45

I've created two functions. I want that when the first one is completed count() the text() function will be executed. But it's not working as expected. Where is the problem?

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

 Future<void> text()  async{
    print("Done");
 }
  
  

void main()  {
  count().then((value)  {
     text();
  });

  
}
4 Answers

You should await the Future.delayed as it is an asynchronous function.

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

Output:

1
2
3
4
5
6
7
8
9
10
Done

You have to await the Future.delayed and you also need to change the Duration to 1 second:

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

 Future<void> text()  async{
    print("Done");
 }
  
  

void main() async  {
 count().then((value)  {
     text();
  });
}

when there is something future and you use async you must use await in the body with future methods

Future<void> count() async {
    for (var i = 1; i <= 10; i++) {
      await Future.delayed(Duration(seconds: 1), () => print(i)); // here 
    }
  }

 Future<void> text()  async{
    print("Done");
 }
  
  

void main() async  {
 count().then((value)  {
     text();
  });
}

Another alternative way to wait for all the delayed futures, is to use Future.wait:

Future<void> count() =>
  Future.wait([for (var i = 1; i < 10; i++) 
      Future.delayed(Duration(seconds: i), () => print(i))]);

void main() async {
  await count();
  print("Done");
}

This starts all the delayed operations, then waits for all of them.

This generalizes to cases where the operations do not necessarily complete in the order they are started.

Using Future.wait is the way to wait for a number of parallel asynchronous operations, instead of waiting for each individually.

Related