在SharedPreferences上Flutter保存对象

时间:2020-07-08 10:59:46

标签: flutter sharedpreferences

我从我的商务API解析了一个有效的json。除了将添加购物车产品存储到共享首选项外,其他所有功能都工作正常。我该如何实现?我遇到类型错误

'ProductsModel'不是'Map '类型的子类型;

这是我的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']
        );
      }
    }

并且我正在测试仅通过使用此功能来存储ProductsModel

这是我的职能

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

1 个答案:

答案 0 :(得分:0)

步骤1:在您的课程中添加toMap()方法

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

步骤2:将其存储在SharedPreferences中时,请在对象上调用toMap()方法 这将返回当前对象的Map 表示形式。

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

第3步:使用json.encode()将对象转换为String并存储!

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

注意:

  • 不要忘记导入dart:convert
  • 在检索对象时,请不要忘记使用json.decode()

如果您在理解为什么使用json.encode()时遇到麻烦,请尝试在使用该函数之前和之后打印对象,您会注意到,当我们将对象转换为JSON时,它会变成一个很大的String,因此它是我们可以使用“ putString()”方法将其存储在SharedPreferences中。