首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将列表存储在另一个列表中的列表中

将列表存储在另一个列表中的列表中
EN

Stack Overflow用户
提问于 2021-09-12 19:29:13
回答 1查看 177关注 0票数 0

我从一个API得到了这个json响应。

代码语言:javascript
运行
复制
{
    "success": true,
    "routes": [
        {
            "_id": "613cc90623db8f3418f59f50",
            "transit": [
                "Addis Ababa",
                "Gondar"
            ],
            "startingPlace": {
                "country": "Ethiopia",
                "city": "Addis Ababa"
            },
            "destination": {
                "country": "Ethiopia",
                "city": "Addis Ababa"
            },
            "distance": 55,
            "__v": 0,
            "schedule": [
                {
                    "_id": "613e200446560f0508778adf",
                    "boardingDate": "2020-01-01T00:00:00.000Z",
                    "arrivalDate": "2020-02-01T00:00:00.000Z",
                    "driverAssistantId": "612de5d3cf56fc27e8abf629",
                    "routeId": "613cc90623db8f3418f59f50",
                    "__v": 0
                }
            ]
        }
    ]
}

我想在routes中检索schedule列表,这是执行post请求的函数。它返回Schedules模型的列表

代码语言:javascript
运行
复制
Future<List<Schedule>> searchSchedule(SearchScheduleModel model) async {
  String token = await getToken();
  Map<String, String> headers = {
    "Content-Type": "application/json",
    'Authorization': 'Bearer $token'
  };
  final allPlacesURl = Uri.parse("$ipAddress/common/searchBySpAndDes");
  var body = searchScheduleModelToJson(model);

  var response = await http.post(allPlacesURl, headers: headers, body: body);
  if (response.statusCode == 200) {
    var body = schedulesModelFromJson(response.body);
    List<Route> route = body.routes;
    List<Schedule> schedules = [];

    //the error is shown here, how can i map a list within alist

    schedules = route.map((e) => e.schedule);

    return schedules;
  }
  return json.decode(response.body);
}

但是我有这个错误

代码语言:javascript
运行
复制
A value of type 'Iterable<List<Schedule>>' can't be assigned to a variable of type 'List<Schedule>'.

我不知道如何正确地映射它..

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-12 20:11:30

该错误告诉您,您正在尝试将Iterable分配给List。我不能100%确定,因为我看不到Route模型,但在我看来,Route有一个List类型的属性计划。

要修复它,请删除以下行:

代码语言:javascript
运行
复制
schedules = route.map((e) => e.schedule);

并将其替换为以下行

代码语言:javascript
运行
复制
for (var route in routes) {
 schedules.addAll(route.schedule);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69154606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档