【问题标题】:Flutter get all data from list into jsonFlutter 从列表中获取所有数据到 json
【发布时间】:2021-09-05 22:30:17
【问题描述】:

我正在将数据保存在列表中,现在我需要将其发布到我的 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 还是将此列表作为字段添加到 json 中?
  • 如果您想将列表转换为 JSON,那么只需使用 JSON.encode 方法。试试这个,看看你是否遇到任何错误

标签: flutter dart


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-11-29
    • 2019-07-30
    • 1970-01-01
    • 2021-10-15
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2019-01-15
    相关资源
    最近更新 更多