我如何将这个复杂的JsonMap数据传递到flutter Listview中

14ifxucb  于 2023-01-18  发布在  Flutter
关注(0)|答案(1)|浏览(143)

我是flutter的新手,我遇到了这个带有复杂“MAP”json的API。我想要的是在flutter listview中显示国家列表及其详细信息,我如何实现这一点?大多数答案都解释了“LIST”json。

{
"status": "Request is successful",
"message": null,
"data": {
"page": 1,
"last_page": 125,
"page_size": 2,
"countries": [
        {
 "id": "1",
"attributes": {
"name": "Grenada",
 "code": "GD",
"subregion": "Caribbean",
"flag": "https://flagcdn.com/gd.svg",
"postalcode": "",
"latitude": "12.11666666",
"longitude": "-61.66666666",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
  }
 },
  {
"id": "2",
"attributes": {
 "name": "Malaysia",
 "code": "MY",
 "subregion": "South-Eastern Asia",
 "flag": "https://flagcdn.com/my.svg",
  "postalcode": "^(\\d{5})$",
 "latitude": "2.5",
  "longitude": "112.5",
  "createdAt": "2023-01-11T22:15:40.000000Z",
  "updatedAt": "2023-01-11T22:15:40.000000Z"
     }
     }
  ]
  }
  }

我发现这个GitHub project与这些文件jsonmodelClassMainclass的概念,但我的是有一个额外的括号(Map),所以我不知道如何实现目标。
如果有任何建议或最佳编码方式,请帮助我。
这是他们在模型类中创建的,但是,但是它对我不起作用。

class Product {
   final List<Result> results;
    Product({this.results});
    factory Product.fromJson(Map<String, dynamic> data) {
     var list = data['data']['result'] as List;
    List<Result> resultList = list.map((e) => Result.fromJson(e)).toList();
    return Product(
    results: resultList,
    );
    }
    }
dojqjjoe

dojqjjoe1#

可以为CountryAttribute创建两个类

class Country {
  const Country({required this.id, required this.attributes});

  /// Creates a Country from Json map
  factory Country.fromJson(Map<String, dynamic> json) => Country(
        id: json['id'] as String,
        attribute:
            Attribute.fromJson(json['attributes'] as Map<String, dynamic>),
      );

  /// A description for id
  final String id;
  final Attribute attributes;
}
class Attribute {
  const Attribute({
    required this.name,
    required this.code,
    required this.createdAt,
    required this.updatedAt,
  });

  /// Creates a Attribute from Json map
  factory Attribute.fromJson(Map<String, dynamic> json) => Attribute(
        name: json['name'] as String,
        code: json['code'] as String,
        createdAt: DateTime.parse(json['createdAt'] as String),
        updatedAt: DateTime.parse(json['updatedAt'] as String),
      );

  final String name;
  final String code;
  final DateTime createdAt;
  final DateTime updatedAt;
}

解码时:

final res = jsonDecode(json) as Map<String, dynamic>;
  final List<Country> list = (res['data']['countries'] as 
  List<dynamic>)
        .map((e) => Country.fromJson(e))
        .toList();

相关问题