英文:
Flutter Error: The argument type 'List<dynamic>' can't be assigned to the parameter type 'Iterable<Future<dynamic>>'
问题
以下是翻译好的部分:
我正在尝试在一个控制器中发起多个请求。
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<dynamic>' 不是 'Iterable<Future<dynamic>>' 的子类型,位于类型转换中。
<details>
<summary>英文:</summary>
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<dynamic>' is not a subtype of type 'Iterable<Future<dynamic>>' in type cast
</details>
# 答案1
**得分**: 0
The `Future.wait()` method expects an `Iterable<Future>` as an argument, but you're passing a `List` instead. Just remove casting:
```dart
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 a for loop inside the argument:
var results2 = await Future.wait([
for (var url in urls) http.get(Uri.parse(url.split(',')[0])),
]);
英文:
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])),
]);
答案2
得分: -1
- 将
var requests = [];
替换为List<Future<dynamic>> requests = [];
- 将
requests as Iterable<Future>
替换为requests
英文:
Two small changes needed:
- Replace
var requests = [];
withList<Future<dynamic>> requests = [];
- Replace
requests as Iterable<Future>
withrequests
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论