Home > Enterprise >  Async Dart function is not working properly
Async Dart function is not working properly

Time:09-07

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();
  });

  
}

CodePudding user response:

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

CodePudding user response:

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();
  });
}

CodePudding user response:

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();
  });
}
  • Related