【问题标题】:Dart objects in Lists列表中的 Dart 对象
【发布时间】:2021-03-30 04:54:15
【问题描述】:

我是 dart/flutter 的新手。

如何使用列表中的对象?

我有这样的对象:

{
    "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
}]

【问题讨论】:

    标签: arrays list flutter dart


    【解决方案1】:

    你可以试试这样的:

    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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-24
      • 2020-06-02
      • 1970-01-01
      • 2022-01-09
      • 2021-09-04
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多