简体   繁体   English

将JSON字符串转换为flutter中的列表对象

[英]convert JSON String to the list object in flutter

I'm still new to the dart flutter. 我对飞镖还是陌生的。 now I'm trying to pull data from the REST API. 现在,我正在尝试从REST API中提取数据。 following the script that I have made: 按照我编写的脚本:

class ChatCard {
  final String chatdetail_id;
  final String chatdetail_userfullname;
  final String chatdetail_userurlphoto;
  final String chatdetail_message;
  final int chatdetail_isread;
  final String chatdetail_datetime;

  ChatCard({
    this.chatdetail_id,
    this.chatdetail_userfullname,
    this.chatdetail_userurlphoto,
    this.chatdetail_message,
    this.chatdetail_isread,
    this.chatdetail_datetime
  });

  factory ChatCard.fromJson(Map<String, dynamic> json) {
    return new ChatCard(
      chatdetail_id : json['chatdetail_id'] as String,
      chatdetail_userfullname : json['chatdetail_userfullname'] as String,
      chatdetail_userurlphoto : json['chatdetail_userurlphoto'] as String,
      chatdetail_message : json['chatdetail_message'] as String,
      chatdetail_isread : json['chatdetail_isread'] as int,
      chatdetail_datetime : json['chatdetail_datetime'] as String
    );
  }
}

class ChatCardList extends StatefulWidget {

  List<ChatCard> chatcard;

  ChatCardList({Key key, this.chatcard}) : super(key: key);

  @override
  _ChatCardListState createState() => new _ChatCardListState(chatcard:chatcard);

  ChatCardList.tambah(String message) {
    print("RESULT MESSAGE = " + message); //result on console : [{"createdAt":"2018-08-16T02:38:37.757Z","is_read":1,"_id":"5b74e3ad26c7de02ed664dd2","from_id":"5b74d3f5e0da63027ab03664","from_name":"Ahmad Adiwijaya","from_photo":"","from_device":"Mobile Phone","text":"Kami dari sekolah tinggi yg hanya satu prodi. Apakah lembaga penjaminan mutuh harus 2, yaitu LPM pada level institusi dan UPM pada level prodi?"},{"from_id":"SystemDate","from_name":"System","from_photo":"","text":"2018-08-23T11:26:53.968Z"}]

  }
}

My question is, how do I input the 'RESULT MESSAGE' result data above to class List<ChatCard> chatcard ? 我的问题是,如何将上面的“ RESULT MESSAGE”结果数据输入到List<ChatCard> chatcard

many thank, 多谢,

Are you expecting some like this, 您是否期望这样的事情,

ChatCardList.tambah(String message) {
  List<ChatCard> chatCardList = message
    .map((chatCardJson) => ChatCard.fromJson(chatCardJson))
    .toList();
  print(chatCardList); // [Instance of 'ChatCard', Instance of 'ChatCard']
}

Note: But the keys in the json printed in the console and in the keys in the ChatCard are different. 注:但keys在控制台,并在打印的JSON keysChatCard是不同的。 You might have to revisit that. 您可能需要重新访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM