Ad

Parsing Data In Model Class In Dart _type Error?

- 1 answer

I am learning Dart and Flutter. Now I am tasting JSON as a persistence method. I get lots of errors, all concerning Types and stuff. This is the latest error I have experienced: _TypeError (type 'List' is not a subtype of type 'Map')

_TypeError (type 'String' is not a subtype of type 'Map')

static Resource<List<ProductImage>> get all {    
    return Resource(
      url: Constants.HEADLINE_NEWS_URL,
      parse: (response) {

    String jsonProduct = response.body;
     final jsonResponse = json.decode(jsonProduct);    
   Product product = new Product.fromJson(jsonResponse);   

        return product.images.toList();

      //return list.map((model) => NewsArticle.fromJson(model));

      }
    );
}

My Model :

        class Product {
        final String id; 
        final List<ProductImage> images;

      Product({this.id, this.images});

        factory Product.fromJson(Map<String, dynamic> parsedJson){

        var list = parsedJson['IDEPELTION'] as List;
        print(list.runtimeType);
        List<ProductImage> imagesList = list.map((i) => ProductImage.fromJson(i)).toList();


        return Product(
          id: parsedJson['DATAS'],
          images: imagesList

        );
      }


    }

    class ProductImage {
      final String itemName;
      final String iCategory;
     // bool isCheck;

      ProductImage({this.itemName, this.iCategory});

      factory ProductImage.fromJson(Map<String, dynamic> parsedJson){
       return ProductImage(
         itemName:parsedJson['ITEM_NAME'],
         iCategory:parsedJson['CATEGORY'],
         //isCheck:false
       );
      }
    }

this is my sample json return the list data to get all method

{"DATAS":"1","IDEPELTION":[{"ITEM_NAME":TRUEMETRIX ,"CATEGORY":"MOUTHPIECE"},{"ITEM_NAME":MULTISTIX 10SG 2161,"CATEGORY":"MOUTHPIECE"}]}
Ad

Answer

Change:

String jsonProduct = response.body;

Into this:

Map<String,dynamic> jsonProduct = response.body;

Since the response is of type Map

Ad
source: stackoverflow.com
Ad