Flutter错误:参数类型’List‘无法赋值给参数类型’Iterable>’。

huangapple go评论60阅读模式
英文:

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&#39;m trying multiple request in a controller. 

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

    var results = await Future.wait(requests as Iterable&lt;Future&gt;);
    for(int i = 0; i &lt; results.length; i++){
      saveData(urls[i].split(&#39;,&#39;)[1], results[i]);
    }

So it give an error.

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: type &#39;List&lt;dynamic&gt;&#39; is not a subtype of type &#39;Iterable&lt;Future&lt;dynamic&gt;&gt;&#39; 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&lt;Future&gt; as an argument, but you're passing a List instead. Just remove casting:

  var requests = &lt;Future&gt;[];
  for (var url in urls) {
    requests.add(http.get(Uri.parse(url.split(&#39;,&#39;)[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(&#39;,&#39;)[0])),
  ]);

答案2

得分: -1

  1. var requests = []; 替换为 List&lt;Future&lt;dynamic&gt;&gt; requests = [];
  2. requests as Iterable&lt;Future&gt; 替换为 requests
英文:

Two small changes needed:

  1. Replace var requests = []; with List&lt;Future&lt;dynamic&gt;&gt; requests = [];
  2. Replace requests as Iterable&lt;Future&gt; with requests

huangapple
  • 本文由 发表于 2023年6月15日 01:12:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定