0

I have a working json parsing from my commerce API. all are working fine except for storing the add cart product to the shared preferences. How can I achieve this? I got an error of type

'ProductsModel' is not a subtype of type 'Map<String, dynamic>';

Here's my ProductsModel

    class ProductsList{
      final List<ProductsModel> products;
      ProductsList({this.products});
      factory ProductsList.fromJSON(List<dynamic> parsedJson){
        List <ProductsModel> productsList = new List<ProductsModel>();
        productsList = parsedJson.map((i) => ProductsModel.fromJSON(i)).toList();
        return new ProductsList(
          products: productsList
        );
      }
    }
    class ProductsModel {
      final int id;
      final String name;
      final String catalog_visibility;
      final String description;
      final String short_description;
      final String price;
      final String regular_price;
      final String sale_price;
      final String date_created;
    
      final List<CategoriesModel> categories;
      final List<ImagesModel> images;
      ProductsModel(
          {this.id,
          this.name,
          this.catalog_visibility,
          this.description,
          this.short_description,
          this.price,
          this.regular_price,
          this.sale_price,
          this.date_created,
          this.categories,
          this.images
          });
    
      factory ProductsModel.fromJSON(Map<String, dynamic> parsedJson) {
        var categoriesList = parsedJson['categories'] as List;
        var imagesList = parsedJson['images'] as List;
        List<ImagesModel> dataImages = imagesList.map((i) => ImagesModel.fromJSON(i)).toList();
        List<CategoriesModel> dataCategories =
        categoriesList.map((i) => CategoriesModel.fromJSON(i)).toList();
        return ProductsModel(
          id: parsedJson['id'],
          name: parsedJson['name'],
            catalog_visibility: parsedJson['catalog_visibility'],
            description: parsedJson['description'],
            short_description: parsedJson['short_description'],
            regular_price: parsedJson['regular_price'],
            sale_price: parsedJson['sale_price'],
            date_created: parsedJson['date_created'],
            categories: dataCategories,
          images: dataImages
        );
    
      }
    }
    
    class CategoriesModel {
      final int id;
      final String name;
    
      CategoriesModel({this.id, this.name});
      factory CategoriesModel.fromJSON(Map<String, dynamic> parsedJson) {
        return CategoriesModel(id: parsedJson['id'], name: parsedJson['name']);
      }
    }
    
    class ImagesModel{
      final int id;
      final String src;
      final String name;
    
      ImagesModel({this.id,this.src,this.name});
      factory ImagesModel.fromJSON(Map<String,dynamic> parsedJson){
        return ImagesModel(
          id: parsedJson['id'],
          src: parsedJson['src'],
          name: parsedJson['name']
        );
      }
    }

and I am testing to stored the ProductsModel only by using this function only

Here's my function

storedCart(products){
     SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('cart', products);
}

1 Answer 1

5

STEP 1 : Add a toMap() method in your class

Map<String,dynamic> toMap() {
    var map = new Map<String, dynamic>();
    map["id"] = id;
    map["name"] = name;
    map["description"] = description;
    // Add all other fields
    return map;
  }

STEP 2 : While storing this in SharedPreferences call the toMap() method on the object This will return a Map<String,dynamic> representation of your current object.

Map<String,dynamic> productsMap = products.toMap();

STEP 3 : Convert the object to String by using json.encode() and store it !

storedCart(productsMap){
     SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('cart', json.encode(productsMap));
}

Note :

  • Dont forget to import dart:convert
  • While retrieving the object don't forget to use json.decode()

If you are having trouble understanding why we used json.encode(), try printing the object before and after using the function, you'll notice that when we convert our object to JSON it becomes a big String, Therefore it is possible for us to store it in SharedPreferences using the "putString()" method.

Sign up to request clarification or add additional context in comments.

2 Comments

I am kinda lost. how about on the Images Model and Categories? do I need to add also a toMap() method?
I got it now. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.