How to run multiple Dart futures in parallel

 


How to run multiple Dart futures in parallel

If you ever need to run multiple Dart futures in parallel (simultaneously), I can confirm that this approach works:

import 'dart:async';

Future<int> async1() async {
    await Future<String>.delayed(const Duration(seconds: 1));
    return 10;
}

Future<int> async2() async {
    await Future<String>.delayed(const Duration(seconds: 2));
    return 20;
}

Future<int> async3() async {
    await Future<String>.delayed(const Duration(seconds: 3));
    return 30;
}

void main() {  //<- 'async' is not necessary here
    var t1 = DateTime.now();
    Future.wait([async1(), async2(), async3()])
          .then((List<int> nums) {
              var t2 = DateTime.now();
              var sum = nums.reduce((curr, next) => curr + next);
              print('sum = $sum');
              print('delta = ${t2.difference(t1)}');  // should be 3, not 6
          });  
}
sum = 60
delta = 0:00:03.006000

Key to running multiple futures in parallel

The biggest key to the solution is this code:

Future.wait([async1(), async2(), async3()])
    .then((List<int> nums) {

Post a Comment

Previous Post Next Post

Subscribe Us


Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter

100% value, 0% spam. Unsubscribe anytime