简体   繁体   中英

How to add an Element (list) into an JSON. Flutter

How I get a list/elements in an Json. To get the input i use this:

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);
}

Now, i get {"Product_Name":"Test","Expiry_date":"12","Stock":1,"Notifications":true} . This, I would now like to add this into a json file. The json file should have more or less this structure:

[
    {
      "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"
    }
  ]

instead of "enterJson" use below code in "OverviewProduct Class":

 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']
);

}

and use it as this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM