skip to Main Content

I’m trying multiple request in a controller.

var requests = [];
for(var url in urls){
  requests.add(http.get(Uri.parse(url.split(',')[0])));
}

var results = await Future.wait(requests as Iterable<Future>);
for(int i = 0; i < results.length; i++){
  saveData(urls[i].split(',')[1], results[i]);
}

So it give an error.

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: type ‘List’ is not a subtype of type ‘Iterable<Future>’ in type cast

2

Answers


  1. The Future.wait() method expects an Iterable<Future> as an argument, but you’re passing a List instead. Just remove casting:

      var requests = <Future>[];
      for (var url in urls) {
        requests.add(http.get(Uri.parse(url.split(',')[0])));
      }
    
      var results = await Future.wait(requests);
    

    Or you can directly run for loop inside the argument:

      var results2 = await Future.wait([
        for (var url in urls) http.get(Uri.parse(url.split(',')[0])),
      ]);
    

    Login or Signup to reply.
  2. 2 small changes needed:

    1. Replace var requests = []; with List<Future<dynamic>> requests = [];
    2. Replace requests as Iterable<Future> with requests
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search