在 Flutter 中将对象存储到本地存储中或从本地存储中检索对象

时间:2020-12-30 10:38:57

标签: json flutter dart serialization

有两个类。 产品类和特性类。

class Product {
  int id;
  String price;
  String description;
  List<Characteristic> characteristics;

  Product({
    @required this.id,
    @required this.price,
    @required this.description,
    this.characteristics,
  });

  factory Product.fromJson(Map<String, dynamic> json) {
    var characteristics = new List<Characteristic>();
    json['characteristics'].forEach((v) {
      characteristics.add(Characteristic.fromJson(v));
    });

    return Product(
      id: json['id'],
      price: json['price'].toString(),
      description: json['description'],
      characteristics: characteristics,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      "id": this.id,
      "price": this.price,
      "description": this.description,
      "characteristics": this.characteristics,
    };
  }
}
class Characteristic {
  int id;
  String name;
  int amount;

  Characteristic({
    this.id,
    this.name,
    this.amount,
  });

  factory Characteristic.fromJson(Map<String, dynamic> json) {
    return Characteristic(
      id: json['id'],
      name: json['name'],
      amount: json['amount'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      "id": this.id,
      "name": this.name,
      "amount": this.amount,
    }
  }
}

我从服务器获取产品。

List<Product> products = fetchProducts();

然后我将产品保存在本地存储中。

void saveProductsToSharedPrefs(List<Product> products) {
    List<String> productIds = [];
    products.forEach((product) {
      Preference.saveValue(key: product.id, value: jsonEncode(product));
      productIds.add(product.id);
    });
    Preference.saveValue(
        key: "ProductIds", value: json.encode(productIds));
  }

在下面的函数中,我必须从本地存储中检索数据并重建产品对象。

Future<List<Product>> getProductsFromSharedPrefs() async {
    String productIdsString =
        await Preference.getValue(key: "ProductIds");
    List<dynamic> productIdsList = json.decode(productIdsString);
    List<Product> products = [];
    productIdsList.forEach((productId) async {
      String productString =
          await Preference.getValue(key: productId.toString());
      final decodedProductString = jsonDecode(productString);
      ...
      ????
    });
    return products;
  }

我被困在这里,不知道该怎么办。

复杂的是 Product 类有一个 characteristics 属性,它是 List<Characteristic> 类型,我不知道如何解码它..

0 个答案:

没有答案