【问题标题】:How to add an Element (list) into an JSON. Flutter如何将元素(列表)添加到 JSON 中。扑
【发布时间】:2021-03-24 06:11:15
【问题描述】:

如何在 Json 中获取列表/元素。为了获得输入,我使用这个:

enterJson(productName, expirydDate, stock, notifications) {
  OverviewProduct overviewProduct =
      OverviewProduct(productName, expirydDate, stock, notifications);

  Map<String, dynamic> map = {
    'Product_Name': overviewProduct.productName,
    'Expiry_date': overviewProduct.expirydDate,
    'Stock': overviewProduct.stock,
    'Notifications': overviewProduct.notifications
  };

  String rawJson = jsonEncode(map);
  print(rawJson);
}

现在,我收到{"Product_Name":"Test","Expiry_date":"12","Stock":1,"Notifications":true}。这个,我现在想把它添加到一个 json 文件中。 json文件应该或多或少有这样的结构:

[
    {
      "Product_Name": "Pom-Bär Original",
      "Expiry_date" : "10.05.21",
      "Stock" : "1",
      "Notifications" : "True"
    },    
    {
      "Product_Name": "Ja! Natürliches Mineralwasser",
      "Expiry_date" : "23.11.21",
      "Stock" : "1",
      "Notifications" : "True"
    }
  ]

【问题讨论】:

    标签: arrays json list flutter


    【解决方案1】:

    在“OverviewProduct Class”中使用下面的代码代替“enterJson”:

     factory OverviewProduct.fromMap(Map<String, dynamic> map) {
      return new OverviewProduct(
      Product_Name: map['Product_Name'],
      Expiry_date: map['Expiry_date'] ,
      Stock: map['Stock'] ,
      Notifications: map['Notifications']
    );
    

    }

    并像这样使用它:

    (map['Products']).map((p) => OverviewProduct.fromMap(p)).toList()
    

    【讨论】:

    • 谢谢,但这只会增加一个新的方法来打印/做其他事情,那就是在 Json 中。但我想从 Json 文件中的用户输入中获取。所以如果我输入: Productname: Test ExpiryDate: 12.12.12 Stock: 1 Notifications: true, 那在 Json 中是:[ ... { "Product_Name": "Test", "Expiry_date" : "12.12.12", "Stock" : "1", "Notifications" : "true" }, ... ]
    猜你喜欢
    • 2015-08-01
    • 2014-06-16
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多