Last Updated: February 25, 2016
·
497
· iaincampbell

Futures & Iterables in Dart

What happens if you need to loop over an iterable and perform a function that returns a future on each item?

If you aren't concerned about the order that the results are returned, you can use Future.wait and map the iterable like so:

Future<String> doSomething() {
    var completer = new Completer();
    List v = [];
    v['something'] = 'something';
    Future.wait(my_list.map((item) => item.itemFunc())).then((List results) {
        v['results'] = results;
        var str = JSON.encode(v);
        completer.complete(str);
    }).catchError((e) {
      print('There was an error: $e');
      completer.complete('');
    });
    return completer.future;
}