i want save list of object in local memory by shared_preferences
my Model :
class Vehicle {
final String vehicleId;
final String vehicleType;
Vehicle({
this.vehicleId,
this.vehicleType,
});
}
after when i search about this i found half-solution :) to convert to List<String>
and add this to my class :
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,
};
}
but i can't found how can i save and get it :(
sorry my English not good
CodePudding user response:
Actually you cannot save a list of object with shared preferences but you can encode each object into a string and save it using setStringList() function
Example:
List<String> vehiculesEncoded = [];
vehicles.forEach((vehicule) {
vehiculesEncoded.add(vehicule.toJson());
});
sharedPreferences.setStringList("myAmazingListOfVehicules", vehiculesEncoded);
CodePudding user response:
this type of array you have & you want to store it in session
List<Vehicle> arrayVehicle = [ your data ];
for that you have to convert array into json string by doing this
String strTemp = json.encode(arrayVehicle);// store this string into session
whenever you want to retrive it just decode that string
List<Vehicle> arrayVehicle = json.decode(yourSessionValue)