How can I store list map object in share preference in flutter

Viewed 194

I have a list of map and I want to store in share preference.How can I do that.Any example?I share my list of map.

playlist = [{'id':1,
             'album':'Test',
             'url':''},
             {'id':2,
             'album':'Test',
             'url':''}
]

1 Answers

To save a List in SharedPreference you can simply encode it to json by doing so it will be converted to string and after using setString function you can save that in Shared Preference and decode it back when getting from Shared Preference. Like below :

List list = ["abc","bcd","efg"];

final jsonData = jsonEncode(list);

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("mykey", jsonData);

print(prefs.getString("mykey")); // to print json data
final List list1 = jsonDecode(prefs.getString("mykey").toString());
print(list1);
Related