dart Flutter误差:无法将参数类型“List< dynamic>”分配给参数类型“Iterable&lt; Future < dynamic>&gt;”

nnt7mjpx  于 2023-06-19  发布在  Flutter
关注(0)|答案(2)|浏览(143)

我在控制器中尝试多个请求。

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]);
}

所以它给予了一个错误。
[VERBOSE-2:dart_vm_initializer.cc(41)]未处理的异常:类型“List”不是类型强制转换中类型“Iterable”的子类型

edqdpe6u

edqdpe6u1#

Future.wait()方法需要一个Iterable<Future>作为参数,但您传递的却是一个List。只需要删除铸造:

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

  var results = await Future.wait(requests);

或者你可以直接在参数中运行for循环:

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

zpgglvta2#

需要2个小改动:
1.将var requests = [];替换为List<Future<dynamic>> requests = [];
1.将requests as Iterable<Future>替换为requests

相关问题