flutter - Flutter 如何将 List 与 JSON 相互转换
问题描述
我使用两个函数将两个字符串变量转换为 JSON 和 JSON。
String toJson() {
Map<String,dynamic> map = {'name': name,'count':checkListCount,'description':description,};
return jsonEncode(map)
}
fromJson(String context){
Map<String,dynamic> map = jsonDecode(contents)
name = map['name'];
description = map['description'];
return '0';
}
我如何使用它来隐藏列表?有我的清单
List<CheckListPoint> checkListPoints = [];
CheckListPoint{
bool correctly = false;
bool passed = false;
String requirement = '';
}
我在 CheckListPoint 中拥有的变量将由用户稍后在应用程序中更改。
解决方案
从 firebase 获取消息时,我做了一件非常相似的事情。这与从 JSON 解析相同,因为这两个值都是动态的。
在这里,我将DataSnapshot转换为List
Future<List<Message>> getMessages(DataSnapshot snapshot) async {
List<Message> msgs = List.empty(growable: true);
if(snapshot.value != null) {
Map<dynamic, dynamic> messages = snapshot.value;
messages.forEach((key, value) {
msgs.add(Message.fromFirebase(value));
});
}
return msgs;
}
这是消息类:
class Message {
String message;
String senderId;
int time;
Message.fromFirebase(Map<dynamic, dynamic> json) :
message = json["message"],
senderId = json["senderId"],
time = json["time"];
}
推荐阅读
- spring - 测试 WebFlux 功能路由
- reactjs - 使用地图在 React 中渲染多个图像
- c++ - 如何编写程序来生成以下模式?
- javascript - 移动导航javascript问题
- python - 向 api print(response.txt) 添加附加信息
- python - BootstrapError Form
- reactjs - 由于通过了道具,受保护的路线无法访问
- elasticsearch - Trying to filter results from aggregation : Elastic Search
- sql - 通过遍历子查询中的值来执行查询
- python - How can you move text to the end of a line in a docx file using python-docx?