首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型'List<dynamic>‘不是'List<Parking>’的子类型

类型'List<dynamic>‘不是'List<Parking>’的子类型
EN

Stack Overflow用户
提问于 2022-04-29 01:22:11
回答 1查看 51关注 0票数 0

我正在调用一个API,但是我一直试图正确地解析这个JSON响应,但是我没有能够解决这个问题。我调用API,并希望显示数据,但我得到的错误类型'List‘不是'List’或返回'null‘的子类型。我不知道我做错了什么。守则如下:

代码语言:javascript
复制
class Parking {
  String name;
  String adress;
  String description;
  int totalParkingLots;
  int totalFreeParkingLots;
  int latitude;
  int longitude;
  int parkingFees;
  String companyId;
  String status;

  Parking(
      {
      this.name,
      this.adress,
      this.description,
      this.totalParkingLots,
      this.totalFreeParkingLots,
      this.latitude,
      this.longitude,
      this.parkingFees,
      this.companyId,
      this.status,
    });

  Parking.fromJson(Map<String, dynamic> json) {
    name = json['Name'];
    adress = json['Adress'];
    description = json['description'];
    totalParkingLots = json['totalParkingLots'];
    totalFreeParkingLots = json['totalFreeParkingLots'];
    latitude = json['latitude'];
    longitude = json['longitude'];
    parkingFees = json['ParkingFees'];
    companyId = json['companyId'];
    status = json['Status'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['Name'] = this.name;
    data['Adress'] = this.adress;
    data['description'] = this.description;
    data['totalParkingLots'] = this.totalParkingLots;
    data['totalFreeParkingLots'] = this.totalFreeParkingLots;
    data['latitude'] = this.latitude;
    data['longitude'] = this.longitude;
    data['ParkingFees'] = this.parkingFees;
    data['companyId'] = this.companyId;
    data['Status'] = this.status;
    return data;
  }
}
代码语言:javascript
复制
  static Future<List<Parking>> getparkings() async {
    List<Parking> _parkings = [];
    try {
      final uri = Uri.parse(ApiManager.parkingsAPIURL);
      final headers = {'Content-Type': 'application/json'};
      var response = await http.Client().get(
        uri,
        headers: headers,
      );

      int statusCode = response.statusCode;
      print(statusCode);
      var jsonResp = jsonDecode(response.body);

       if (jsonResp != null) {
          _parkings = jsonResp.map((item) => Parking.fromJson(item)).toList();
        }
        return _parkings;
    } catch (e) {
       print(e);
    }
  }

我几乎可以肯定API调用和响应的问题,因为我没有正确地解析JSON数据,但可能是我错了,还有别的问题。

EN

回答 1

Stack Overflow用户

发布于 2022-04-29 09:03:34

它们是正确的,JSON响应没有什么问题,就像@mmcdon20提到的那样,由于某些原因,Flutter无法在map()函数中检测到正确的返回类型。但我猜这与jsonResp有关,因为它是dynamic类型,而dynamic实际上没有map()函数。

但是现在,要解决这个问题,只需将返回类型转换为map()函数,如下所示:

代码语言:javascript
复制
_parkings = jsonResp.map<Parking>((item) => Parking.fromJson(item)).toList();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72051826

复制
相关文章

相似问题

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