Reputation: 611
I'm making a Flutter app for fuel expenses tracking. I have a simple object:
class Entry {
double _fuel;
double _money;
double _distance;
Entry(this._fuel, this._money, this.distance);
Entry.fromJson(Map<String, dynamic> json) => Entry (json['fuel'], json['money'], json['distance']);
Map<String, dynamic> toJson() => {'fuel':_fuel, 'money':_money, 'distance':_distance};
}
Whenever I refill my tank I want to make a new entry and to keep all of them virtually forever. In the app I have a List<Entry> entries
, but I couldn't find a way to save that list in SharedPreferences
. There is only a method which accepts a list of Strings. Should I create a new List<String>
by iterating through my List<Entries>
and serializing each entry, and then saving that list to the SharedPreferences
or is there an easier way? And when I want to read from SharedPreferences
, how can I recreate my list?
Update: Of course, I also need to be able to delete a particular entry from the list.
Thanks.
Upvotes: 3
Views: 2157
Reputation: 727
List<String>
is a viable option indeed, and the other option I can think of is to serialize the whole list as json using json.encode()
method and save it as a string in SharedPreferences, then retrieve and deserialize them and iterate over them to turn them into your custom object again.SharedPreferences prefs = await SharedPreferences.getInstance();
List<Entry> entries = // insert your objects here ;
final String entriesJson = json.encode(entries.map((entry) => entry.toJson()).toList());
prefs.setString('entries', entriesJson);
final String savedEntriesJson = prefs.getString('entries);
final List<dynamic> entriesDeserialized = json.decode(savedEntriesJson);
List<Entry> deserializedEntries = entriesDeserialized.map((json) => Entry.fromJson(json)).toList();
To remove a particular key (with its value) from SharedPreferences simply use the remove(key)
method, or if you are going to use the same key, you can set the key with a new value and it will override the previous value.
To remove a particular item from your List<Entry>
you can use either the remove(entry)
method of the List class
if you can pass the item, or remove an item depending on a certain condition using the removeWhere((entry) => entry.distance > 500)
for example.
Hope that helped.
Upvotes: 6
Reputation: 246
For adding entry
you do not need to serialize all entries, just use getStringList
of SharedPreferences
and add json string
of your entry
to string list, and save again
var sharedPreferences = await SharedPreferences.getInstance();
List<String> entriesStr = sharedPreferences.getStringList(KEY);
entriesStr.add(jsonEncode(entryToAdd.toJson()));
sharedPreferences.setStringList(KEY, entriesStr);
Upvotes: 0