【问题标题】:Perform async operation on list in dart对 dart 中的列表执行异步操作
【发布时间】:2020-07-03 02:16:07
【问题描述】:

我有一个问题,我必须将列表中的某些元素(此处为 types)映射到相同类型但使用异步操作的其他一些元素。

Future<String> getData() async {
  return await "hi";
}

void main() {
  List<String> types = ["", "", ""];
  List<String> otherTypes = types.map((e) async {
    return await getData();
  }).toList();
}

但代码无法编译并出现以下错误。

Error compiling to JavaScript:
main.dart:9:6:
Error: A value of type 'List<Future<String>>' can't be assigned to a variable of type 'List<String>'.
 - 'List' is from 'dart:core'.
 - 'Future' is from 'dart:async'.
  }).toList();
     ^
Error: Compilation failed.

PS:我已经在dartpad.dev 上尝试过上面的代码。

【问题讨论】:

    标签: flutter asynchronous dart async-await


    【解决方案1】:

    List 不能在不使用另一个 for 循环的情况下转换为 Future ,或者您可以创建一个列表并为每个循环使用常规的。示例如下

    Future<String> getData() async {
      return await "hi";
    }
    
    void main() async{
      List<String> types = ["", "", ""];
      List<String> otherTypes = List();
      for(var s in types)
         otherTypes.add(await getData());
    }
    

    附:未来值只能通过异步函数访问,否则必须使用 (future value).then() 回调。

    【讨论】:

    • 为我工作。谢谢:)
    • 其实List&lt;Future&lt;T&gt;&gt;可以用Future.wait转换成Future&lt;List&lt;T&gt;&gt;
    • List&lt;String&gt; otherTypes = [for (var v in types) await getData()];。只要周围的函数是异步的,你就可以在任何地方等待。
    猜你喜欢
    • 2011-03-20
    • 2019-05-27
    • 1970-01-01
    • 2017-06-23
    • 2021-10-12
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多