Home > Back-end >  Dart avait Future, postpone just certain line of code and execute the rest
Dart avait Future, postpone just certain line of code and execute the rest

Time:11-26

Want to have certain lines of code postponed, using await Future for it and it works great, problem is that it postpones all the code after it, I need it to postpone just certain line of code while continuing to execute rest of the code imediately

void main() async {
  for (int i = 0; i < 5; i  ) {
       await Future.delayed(Duration(seconds: 1));
    //postpone just next line or few lines of code
    print('postpone this line of code ${i   1}');
    print('postpone me too');
  }
  //should execute without being postponed
  print('continue imediately without being postponed by await Future');
}

Is this possible with await Future or with some other function?

CodePudding user response:

await it syntactic sugar for registering a Future.then callback. The point of using await is to make it easier to make all of the subsequent code wait for the Future to complete. If that's not what you want, you can use Future.then directly:

void main() {
  for (int i = 0; i < 5; i  ) {
    Future.delayed(Duration(seconds: 1)).then((_) {
      print('postpone this line of code ${i   1}');
      print('postpone me too');
    });
  }
  print('continue immediately without being postponed by await Future');
}
  • Related