0

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

Sparkat JKS
  • 149
  • 1
  • 10

2 Answers2

0

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);
  • thanks for reply .. i get error >( The argument type 'Map' can't be assigned to the parameter type 'String'. ) in this line (vehiculesEncoded.add(vehicule.toJson());) – Sparkat JKS Oct 07 '22 at 21:42
  • This could be fixed by changing **vehiculesEncoded.add(vehicule.toJson());** into **vehiculesEncoded.add(jsonEncode(vehicule.toJson()));** Wrapping **toJson** with **jsonEncode()** will solve that issue. – ThisIsMonta Oct 08 '22 at 23:51
0

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)
            
Dharini
  • 700
  • 7
  • 20