SharedPrefrences allows you to store a json.
So What I suggest is add a toMap() method to Event class:
Map<String, dynamic> toMap() {
return {
'imagePath': imagePath,
'title': title,
'eventId': eventId,
...
};
}
And a function that create a map of all the events:
Map<String, dynamic> todoEventosMap() {
Map<String, dynamci> map;
todoEventos.forEach((event) {
// eventId should be unique
map[event.eventId] = event.toMap();
});
return map;
}
Then u can encode the map to json and save.
import 'dart:convert';
await prefs.setString('events', json.encode(todosEventosMap()));
To get back the list from sharedPreferences:
You can add a convenience factory method for Event:
factory Event.fromMap(Map<String,dynamic> map) {
return Event(
imagePath = map['imagePath'],
title = map['title'],
eventId = map['eventId'],
...
);
}
When creating todoEventos pass the map to the factory:
List<Event> todoEventos;
var events = json.decode(await prefs.getString('events')) as Map<String, dynamic>;
events.forEach((eventId, eventMap) => todoEventos.add(Event.fromMap(eventMap)));