I want to save a list of objects into my local memory using the shared_preferences
package.
Let's assume that this is my class:
class Person{
String name;
String age;
String gender;
}
How do I do that with shared_preferences
?
I am looking forward to hearing from all of you. Thank you.
You can save a List<String>
with shared_preferences
.
Therefore, we need to convert the Person
class, and its list, into a String
by encoding them as JSON
:
class Person {
String name;
String age;
String gender;
Person({this.name, this.age, this.gender});
factory Person.fromJson(Map<String, dynamic> parsedJson) {
return new Person(
name: parsedJson['name'] ?? "",
age: parsedJson['age'] ?? "",
gender: parsedJson['gender'] ?? "");
}
Map<String, dynamic> toJson() {
return {
"name": this.name,
"age": this.age,
"gender": this.gender,
};
}
}
void _savePersons(List<Person> persons) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
List<String> personsEncoded = persons.map((person) => jsonEncode(person.toJson())).toList();
await sharedPreferences.setStringList('persons', personsEncoded );
}
In the same fashion, we can get the saved List<Person>
as a JSON
object and de-serialize it:
List<Person> _getPersons(List<Person> persons) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final persons = await sharedPreferences.setStringList('persons', accounts);
return persons.map((person) => Person.fromJson(person)).toList();
}