我想通过shared_preferences
将对象列表保存在本地内存中我的模型:
class Vehicle {
final String vehicleId;
final String vehicleType;
Vehicle({
this.vehicleId,
this.vehicleType,
});
}
之后,当我搜索这个时,我找到了一半的解决方案:(转换为List<String>
,并将其添加到我的类中:
factory Vehicle.fromJson(Map<String, dynamic> vehicleJson){
return new Vehicle(
vehicleId: vehicleJson['vehicleId'],
vehicleType: vehicleJson['vehicleType'],
);
}
Map<String, dynamic> toJson(){
return {
'vehicleId': this.vehicleId,
'vehicleType' : this.vehicleType,
};
}
但我找不到如何保存和获取:(
对不起,我的英语不好
实际上,您无法保存具有共享首选项的对象列表,但您可以将每个对象编码为字符串,并使用setStringList((函数保存
示例:
List<String> vehiculesEncoded = [];
vehicles.forEach((vehicule) {
vehiculesEncoded.add(vehicule.toJson());
});
sharedPreferences.setStringList("myAmazingListOfVehicules", vehiculesEncoded);
您拥有的这种类型的数组&您想将其存储在会话中
List<Vehicle> arrayVehicle = [ your data ];
为此,您必须通过执行将数组转换为json字符串
String strTemp = json.encode(arrayVehicle);// store this string into session
每当你想检索时,只需解码字符串
List<Vehicle> arrayVehicle = json.decode(yourSessionValue)