我正在尝试从/到共享首选项中保存和检索自定义对象列表。
这是我的保存功能
save(String key, value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(value));
print(json.encode(value));
}
我正在保存产品列表:
import 'category.dart';
import 'image.dart';
import 'rating.dart';
class Product{
int id;
String name_en,
name_ar,
description_en,
description_ar,
original_price,
stock,
final_price;
bool has_sale;
Category category;
Rating rating;
Image main_image;
Product(
{this.main_image,
this.name_en,
this.name_ar,
this.category,
this.description_ar,
this.description_en,
this.final_price,
this.has_sale,
this.rating,
this.original_price,
this.stock});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
main_image: json['main_image'] != null
? Image.fromJson(json['main_image'])
: null,
name_en: json['name_en'],
name_ar: json['name_ar'],
description_en: json['description_en'],
description_ar: json['description_ar'],
original_price: json['original_price'],
final_price: json['final_price'],
category: Category.fromJson(json['category']),
rating: Rating.fromJson(json['rating']),
has_sale: json['has_sale']
);
}
Map<String, dynamic> toJson() => {
'main_image': main_image,
'name_en': name_en,
'name_ar': name_ar,
'description_en': description_en,
'description_ar': description_ar,
'original_price': original_price,
'final_price': final_price,
'category': category,
'rating': rating,
'has_sale': has_sale
};
}
它工作正常..这是我正在检索的数据函数
read(String key) async {
final prefs = await SharedPreferences.getInstance();
return json.decode(prefs.getString(key));
}
我的问题在尝试将json转换为产品列表时发生,这是我的工作
var productsFromShared = await sharedPref.read("product");
var listNewProducts = productsFromShared as List;
List<Product> list =
listNewProducts.map((i) => Product.fromJson(i)).toList();
我错过了什么?
答案 0 :(得分:0)
要获取数据功能的详细信息,请添加以下代码:
class Product{
Future<void> loadPastDetails() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String storeKey = prefs.getString("Key");
if (storeUser != null) { // Load store key
Map<String, dynamic> jsonValue = json.decode(storeKey);
print('Details $storeKey');
// Do update operations
}
}
}
更新从JSON转换为值。
Future<void> updateDetails(Map<String, dynamic> jsonValue) async {
name_en = jsonValue['name_en'] ?? this. name_en;
name_ar = jsonValue['name_ar'] ?? this. name_ar;
// and so on..
print(name_en);
}
希望这会有所帮助!