dart - 在 Dart 中向服务器发出多个独立请求的最佳方式

我想以最佳方式向同一服务器发出多个请求。所以我有

Future<List<Item>> getAllItems() async {
    var client = new http.Client();
    List<String> itemsIds = ['1', '2', '3']; //different ids
    List<Item> itemList = [];
    for (var item in itemsIds) {
      //make call to server eg: 'sampleapi/1/next' etc
      await client.get('sampleapi/' + item + '/next').then((response) {
        //Do some processing and add to itemList

      });
    }
    client.close();
    return itemList;
}

现在,api 调用一个接一个。但是 api 调用是相互独立的。避免异步等待 hell 的最佳实现方式是什么?

最佳答案

您可以使用 Future.wait(...) 等待一组 Future 完成:

Future<List<Item>> getAllItems() async {
    var client = new http.Client();
    List<String> itemsIds = ['1', '2', '3']; //different ids

    return Future.wait<Item>(['1', '2', '3'].map((item) =>
      client.get('sampleapi/' + item + '/next').then((response) {
        //Do some processing and add to itemList
        return foo; // some Item that is the result of this request 
      });
    );
}

另见 https://api.dartlang.org/stable/1.24.3/dart-async/Future/wait.html

https://stackoverflow.com/questions/50027632/

相关文章:

build - 如何在 Flutter 中修复 "Gradle build failed to pr

dart - 在 Flutter 中调用 showTimePicker() 时如何使用 24 小时制

android - 如何设置 Flutter 应用的构建和版本号

flutter - 控制和禁用 flutter 中的下拉按钮?

image - Flutter CircleAvatar backgroundImage没有填满圆圈

listview - 如何通过 Flutter 中的 RaisedButton 传递/绑定(bind

dart - 这个 Dart 错误处理程序有什么问题?

sqlite - 如何在 Flutter 中使用 SQFlite 进行数据库查询

firebase - Flutter如何使用Future返回值作为变量

firebase - 如何在 Flutter 中从 Firebase Auth 获取用户 ID?