flutter - Flutter 从列表中获取所有数据到 json
问题描述
我正在将数据保存在列表中,现在我需要将其发布到我的 api,所以我需要将其转换为 json,但我被卡住了如何调用所有数据列表
我的代码
class DiagCollection with ChangeNotifier {
List<Items_other> otheritems = [];
void addOthers(Items_other day) {
otheritems.add(day);
print(otheritems);
notifyListeners();
}
void removeOthers(int index) {
otheritems.removeAt(index);
notifyListeners();
}
}
class Items_other {
String name;
String comments;
int id;
Items_other({this.name, this.comments, this.id});
Map<String, dynamic> toJson() => {
'name': name,
'comments': comments,
'id': id,
};
}
我正在插入这样的数据
final collection = Provider.of<DiagCollection>(context);
collection
.addOthers(Items_other(
name: "Allergies",
id: otherAllergiesselect,
comments: otherAllergiesselectText.text,
));
现在我需要在 json 中获取所有 addOthers 列表
解决方案
据我了解,您正在尝试将对象列表转换为 json 列表。如果我是真的,它是以下存储库的副本。将列表转换为 jsons 您不能将列表转换为对象。您需要按元素应用它然后转换为 json。
var json = jsonEncode(yourlistofobject.map((e) => e.toJson()).toList());
推荐阅读
- c# - c# 只返回一个对象请求的属性
- node.js - Postgres 使用 TypeOrm 级联删除:表“table1”上的更新或删除违反了表“table2”上的外键约束
- netty - MessageListener 停止监听 HornetQ 队列
- javascript - 向 Javascript 对象添加属性
- c++ - 如何使用 std::unique 删除向量中的唯一字符(C++)
- javascript - 在鼠标光标悬停时播放选定的视频/光标关闭时暂停
- oracle - 循环遍历数组以获取 where 条件 pl/sql
- php - 在codeigniter中上传图片Rest api
- android - 在特定设备上使用 Let's Encrypt 的 ERR_SSL_PROTOCOL_ERROR
- java - 无法使用 Groovy/Grails Tool Suite 在 grails 项目中打开文件