我使用共享首选项通过保存 json 来保存我的对象。 这一切在 Android Studio 中工作正常,但如果我在手机上尝试它,当我启动应用程序时,它不会保存/加载我的对象。
这是我加载共享首选项的地方
List<String> productName = [];
List<String> productUnit = [];
List<double> productPrice = [];
List<String> productImage = [];
List<int> productStock = [];
List<String> productCurrency = [];
late SharedPreferences sharedPreferences;
@override //Initialises the sharedPreference data
void initState() {
super.initState();
initialGetSavedData();
}
// Function that loads sharedPreference
void initialGetSavedData() async {
final prefs = await SharedPreferences.getInstance();
final keys = prefs.getKeys();
prefs.clear();
//This is how it was just in case final prefsMap = Map<String, dynamic>();
//ToDO check if I have to reverse it
final prefsMap = <String, dynamic>{};
for(String key in keys) {
prefsMap[key] = prefs.get(key);
Product product = Product.fromJson(jsonDecode(prefsMap[key]));
setState(() {
productName.add(product.name);
productUnit.add(product.unit);
productPrice.add(product.price);
productImage.add(product.image);
productStock.add(product.stock);
productCurrency.add(product.currency);
});
}
}
这就是我在 SharedPreferences 中保存的方式
save(String key, value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(value));
}
这就是我的课
class Product{
late String name;
late String unit;
late String image;
late double price;
late int stock;
late String currency;
Product({required this.name, required this.price, required this.unit, required this.image, required this.stock, required this.currency});
//Method that converts json to object instance
Product.fromJson(Map<String, dynamic> json){
name = json['name'] as String;
price = json['price'] as double;
unit = json['unit'] as String;
image = json['image'] as String;
stock = json['stock'] as int;
currency = json['currency'] as String;
}
//Method that converts object to json String
Map<String, dynamic> toJson() => {
'name': name,
'price': price,
'unit': unit,
'image': image,
'stock': stock,
'currency': currency,
};
}
我现在的问题是,如何修复我的硬件 android?
我尝试重新安装该应用程序,并在安装后尝试将其与电脑断开连接。 但这并没有帮助。
NVM
在initialGetSavedData()中我调用prefs.clear(); 所以我在启动应用程序时删除了所有保存的数据