How to save a List<type> in Shared Prefrences
The error List<dynamic> instead of List<Contact>
tells you that when you do jsonDecode(prefs.getString('contactList'))
it's deserialized as a List<dynamic>
, if you want it to be of type List<Contact>
you must cast the children to the type you want map((c) => c as Contact)).toList()
.
Encoding:
List<Contact> contacts = [];
SharedPreferences prefs = await SharedPreferences.getInstance();
final encoded = jsonEncode(contacts)
prefs.setStringList('contactList', encoded);
Decoding:
SharedPreferences prefs = await SharedPreferences.getInstance();
contacts = jsonDecode(prefs.getString('contactList')).map((c) => c as Contact)).toList();
Anan Saadi
Updated on December 31, 2022Comments
-
Anan Saadi 11 months
The list is type
Contact
, which is a Class acquired fromcontacts_service
package.I tried to save it by first
jsonEncode
and then saving it as a List:List<Contact> contacts = []; void saveContacts() async{ SharedPreferences prefs = await SharedPreferences.getInstance(); final encoded = jsonEncode(contacts) prefs.setStringList('contactList', encoded); }
and loading it with:
void loadContacts(){ SharedPreferences prefs = await SharedPreferences.getInstance(); contacts = jsonDecode(prefs.getString('contactList'))
but I got error
List<dynmaic> instead of List<Contact>
So I tried converting it to
Map
:SharedPreferences prefs = await SharedPreferences.getInstance(); var encoded= jsonEncode(contacts, toEncodable: (c) { if (c is Contact) { return c.toMap(); } }); prefs.setStringList('contactList', encoded);
and loading:
SharedPreferences prefs = await SharedPreferences.getInstance(); contacts = (jsonDecode(prefs.getString('List'))as List ).map((e) {return Contact.fromMap(e);});
but I got
String is not a subtype of type 'List<dynamic>' in type cast
So now I have no idea what else to do.
Note : using
Shared Preferences
andJson
is not necessary, and will try to use any other packages if they are better with saving this kind of stuff. -
Anan Saadi over 2 yearsI am getting
type _InternalLinkedHashMap<String, dynamic> is not a subtype of type 'Contact' in type cast
, alsomap
doesn't show up when typing manually so I think there is something wrong with the structure of your code @Daniel Evangelista -
JellyO over 2 yearsThe code above is if you encode it from a
List<Contact>
and not a Map. -
Anan Saadi over 2 yearsI didn't understand exactly what do you mean, can you provide an example @Daniel Evangelista