Flutter 错误:list<dynamic> 不是 Map<dynamic, dynamic> 类型的子类型

时间:2021-06-25 07:42:23

标签: json list flutter dictionary

我的 JSON 有点像这样:

{"data":{"id":1,"title":"Title 1", "images": [{"small": "link", "large": "link"}]}}

我的模型类:

class Test {
final int id;
final String title;
final Images images;

Test({required this.id,
      required this.title,
      required this.images});

Test.fromJson(Map<dynamic, dynamic> parsedJson) :
    id = parsedJson["id"],
    title = parsedJson["title"],
    images = Images.fromJson(parsedJson['images']);

class Images {
  final String small;
  final String large;

Images({
   required this.small,
  required this.large
});


 factory Images.fromJson(Map<dynamic, dynamic> json) {
   return Images(
    small : json["small"] as String,
    large : json["large"] as String
  );}
}

这是我的 api 调用:

 static Future<Test> getTest(int id) async{
    final response = await http.get(Uri.parse("url_here"));
    if(response.statusCode == 200){
      Map<String, dynamic> json = jsonDecode(response.body);
      dynamic body = json['data'];
      Test test = Test.fromJson(body);
      return test;
    }
    else{
      throw("message");
    }
  }

如何在视图类中获取images.small?如果我需要澄清我的问题,请告诉我。我在尝试获取图像时收到错误列表不是 Map 类型的子类型,但我无法将映射转换为列表。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此模型。 :

import 'dart:convert';

Test testFromJson(String str) => Test.fromJson(json.decode(str));

String testToJson(Test data) => json.encode(data.toJson());

class Test {
    Test({
        this.id,
        this.title,
        this.images,
    });

    int id;
    String title;
    List<Images> images;

    factory Test.fromJson(Map<String, dynamic> json) => Test(
        id: json["id"],
        title: json["title"],
        images: List<Images>.from(json["images"].map((x) => Images.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "title": title,
        "images": List<dynamic>.from(images.map((x) => x.toJson())),
    };
}

class Images {
    Images({
        this.small,
        this.large,
    });

    String small;
    String large;

    factory Images.fromJson(Map<String, dynamic> json) => Images(
        small: json["small"],
        large: json["large"],
    );

    Map<String, dynamic> toJson() => {
        "small": small,
        "large": large,
    };
}

此处的图像列表已直接映射到相应的图像类对象,从而解决了您的问题。

答案 1 :(得分:1)

"images": [{"small": "link", "large": "link"}] 这是一个列表映射,您将其转换为字符串映射。
要么使用 "images": {"small": "link", "large": "link"}
或使用

factory Images.fromJson(List<dynamic> json) {
   return Images(
    small : json[0]["small"] as String,
    large : json[0]["large"] as String
  );}