问题
I'm still new to the dart flutter. now I'm trying to pull data from the 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
?
many thank,
回答1:
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. You might have to revisit that.
来源:https://stackoverflow.com/questions/52225846/convert-json-string-to-the-list-object-in-flutter