首页 > 解决方案 > 列表中的 Dart 对象

问题描述

我是飞镖/颤振的新手。

如何使用列表中的对象?

我有这样的对象:

{
    "channelName": "sydneyfunnelaio",
    "type": "",
    "ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
    "success": true
}

我怎样才能用它创建列表/数组;

我想喜欢:

[{
    "channelName": "sydneyfunnelaio",
    "type": "",
    "ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
    "success": true
},{
    "channelName": "qweqdqaw",
    "type": "",
    "ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
    "success": true
}]

标签: arrayslistflutterdart

解决方案


你可以尝试这样的事情:

void main() {
  List<MyObject> myObjects = [];

  myObjects.add(MyObject.fromJson({
    "channelName": "sydneyfunnelaio",
    "type": "",
    "ChannelPic":
        "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
    "success": true
  }));

  myObjects.add(MyObject.fromJson({
    "channelName": "qweqdqaw",
    "type": "",
    "ChannelPic":
        "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
    "success": true
  }));

  print(myObjects);
  print(myObjects[0].channelName);
  print(myObjects[1].channelName);

  myObjects.forEach((obj)=>print(obj.toJson()));

}

class MyObject {
  String channelName;
  String type;
  String channelPic;
  bool success;
  MyObject({this.channelName, this.type, this.channelPic, this.success});
  MyObject.fromJson(Map<String, dynamic> json) {
    channelName = json['channelName'];
    type = json['type'];
    channelPic = json['ChannelPic'];
    success = json['success'];
  }
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['channelName'] = this.channelName;
    data['type'] = this.type;
    data['ChannelPic'] = this.channelPic;
    data['success'] = this.success;
    return data;
  }
}

推荐阅读