Home > Blockchain >  Dart : async function is not working perfectly
Dart : async function is not working perfectly

Time:09-06

I created two function. I want that, at first complete the count() function and then run text() function. But isn't not working. 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
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