首页 > 解决方案 > 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 列表

标签: flutterdart

解决方案


据我了解,您正在尝试将对象列表转换为 json 列表。如果我是真的,它是以下存储库的副本。将列表转换为 jsons 您不能将列表转换为对象。您需要按元素应用它然后转换为 json。

var json = jsonEncode(yourlistofobject.map((e) => e.toJson()).toList());

推荐阅读