gpt4 book ai didi

flutter - 在 flutter 中序列化对象列表并使用共享首选项保存它时出现问题

转载 作者:行者123 更新时间:2023-12-05 04:46:29 24 4
gpt4 key购买 nike

我一直在尝试保存类型为 Contact 的列表(这是来自 contacts_service 的类)通过使用 toJosn 对其进行序列化来打包和 fromJson然后将其保存为 StringShared Preferences

到&从Josn:

 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};

保存和加载:

  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));
}

但我遇到了一个错误 Converting object to an encodable object failed: Instance of 'MappedListIterable<dynamic, Item>'

另请注意,这是我第一次尝试序列化和对象,因此可能遗漏了 to 中的一些内容& fromJosn

编辑:

我也试过使用 toEncodable

final String List = jsonEncode(contacts, toEncodable: (c)=> c.toJson());        

但它会返回一个异常:type 'MappedListIterable<dynamic, Contact>' is not a subtype of type 'List<Contact>'

最佳答案

这可能会解决您的问题:

var contacts = decoded.map((c) => Contact.fromJson(Map<String, dynamic>.from(c)));

关于flutter - 在 flutter 中序列化对象列表并使用共享首选项保存它时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68785393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com