Parsing JSON data into a List (Dart)

Viewed 103

for some reason I migrate from Firbase to Back4app realtime database for my flutter app. I have a shopping app and I store my product data into that database. Previously In firebase I had a code like this to create a new product based on my JSON data , here I use foreach() method to add a product to my list because my response JSON body was <Map , Dynamic> :

    final List<Product> loadedProduct = [];
    var extractedData = jsonDecode(response.body) as Map<String, dynamic>;
  extractedData.forEach((k,v) { 

loadedProduct.add(Product(
     id: k,
     title: v['Title'],
     description:v['Description'], 
     price: v['Price'], 
     imageUrl: v['ImageUrl']));

     });

but when I setup my Bakc4app It has a different type of JSON body :

{results: [{objectId: K9RTu0LBgI, pTitle: laptop, pDescription: macbookpro 2018, pPrice: 60.58, pImageUrl: https://images.unsplash.com/photo-1541807084-5c52b6b3adef?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8bGFwdG9wfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60, isFavorite: false, createdAt: 2021-06-11T10:42:39.185Z, updatedAt: 2021-06-11T10:42:39.185Z}, {objectId: CzzhXFKahu, pTitle: headphone, pDescription: best headphone for gaming , pPrice: 60.55, pImageUrl: https://images.unsplash.com/photo-1505740420928-5e560c06d30e?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aGVhZHBob25lfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60, isFavorite: false, createdAt: 2021-06-11T10:46:32.541Z, updatedAt: 2021-06-11T10:46:32.541Z}, {objectId: e5PiYuLDQZ, pTitle: apple watch, pDescription: apple watch seris 3, pPrice: 85.55, pImageUrl: https://images.unsplash.com/photo-1546868871-7041f2a55e12?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8YXBwbGUlMjB3YXRjaHxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=

and It contains a Map with a List of map how do I create a new product based on this type of JSON??

1 Answers
List<Product> loadedProduct;
    var responseBody= Map<String,dynamic>.from(jsonDecode(response.body));
    var resultList = List<Map<String, dynamic>>.from(responsBody["results"]);
    loadedProducts = resultList.map((Map<String, dynamic> productMap){
      return Product(
     id: productMap["objectId"],
     title: productMap["pTitle"],
     description:productMap['pDescription'], 
     price: double.parse(productMap['pPrice']), 
     imageUrl: productMap['pImageUrl']));

    }).toList()
Related