Problem serializing a list of objects in flutter and saving it using shared preferences
I have been trying to save a list of type Contact
(which is a class from contacts_service
) package by serializing it using toJosn
and fromJson
and then saving it as String
in Shared Preferences
to & fromJosn :
Contact.fromJson(Map<String, dynamic> json):
identifier = json['identifier'],
displayName = json['displayName'],
givenName = json['givenName'],
middleName = json['middleName'],
prefix = json['prefix'],
suffix = json['suffix'],
familyName = json['familyName'],
company = json['company'],
avatar = json['avatar'],
androidAccountType = json['androidAccountType'],
jobTitle = json['jobTitle'],
androidAccountTypeRaw = json['androidAccountTypeRaw'],
androidAccountName = json['androidAccountName'],
emails = json['emails'], phones = json['phones'],
postalAddresses = json['postalAddresses'],
birthday = json['birthday'];
Map<String, dynamic> toJson() => {
'identifier':identifier,
'displayName':displayName,
'givenName':givenName,
'middleName':middleName,
'prefix':prefix,
'suffix':suffix,
'familyName':familyName,
'company':company,
'avatar':avatar,
'jobTitle':jobTitle,
'androidAccountTypeRaw':androidAccountTypeRaw,
'androidAccountName':androidAccountName,
'emails':emails,
'phones':phones,
'postalAddresses':postalAddresses,
'birthday':birthday,
'androidAccountType':androidAccountType};
saving & loading:
void saveContacts() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
final String List = json.encode(contacts.map((contact) => contact.toJson()));
await prefs.setString('contactList', List);
}
void loadConatcs() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
final String saved = prefs.getString('contactList');
final List<dynamic> decoded = json.decode(saved);
contacts = decoded.map((contact) => Contact.fromJson(contact));
}
but I am gettign an error Converting object to an encodable object failed: Instance of 'MappedListIterable<dynamic, Item>'
also note that this is my first time trying to serialize and object so might have missed some things up in to
& fromJosn
edit:
I also tried using toEncodable
final String List = jsonEncode(contacts, toEncodable: (c)=> c.toJson());
but it would return an exception : type 'MappedListIterable<dynamic, Contact>' is not a subtype of type 'List<Contact>'
this probably will solve your problem:
var contacts = decoded.map((c) => Contact.fromJson(Map<String, dynamic>.from(c)));