Объекты Dart в списках

#arrays #list #flutter #dart

#массивы #Список #трепетание #dart

Вопрос:

Я новичок в 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
}]
 

Ответ №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;
  }
}