我正在Flutter项目中开发一个聊天应用。我想将来自API的聊天信息保存到SharedPreferences
。我使用以下模型:
class ChatModel {
String username;
String name;
String lastName;
String icon;
String time;
String lastMessage;
ChatModel(this.username, this.name, this.lastName, this.icon, this.time,
this.lastMessage);
factory ChatModel.fromJson(Map<String, dynamic> json) {
String username = json['username'];
String name = json['name'];
String lastName = json['lastName'];
String icon = json['icon'];
String time = json['time '];
String lastMessage = json['lastMessage '];
return ChatModel(username, name, lastName, icon, time, lastMessage);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['username'] = this.username;
data['name'] = this.name;
data['lastName'] = this.lastName;
data['icon'] = this.icon;
data['time'] = this.time;
data['lastMessage'] = this.lastMessage;
return data;
}
@override
String toString() {
return '{ "username": $username, "name": $name, "lastName": $lastName, "icon": $icon, "time": $time, "lastMessage": $lastMessage}';
}
我使用以下代码来写入/读取SharedPreferences
数据:
//For saving incoming API Json data into shred preferences.
Future<void> saveChatModelInfo() async {
final ChatModel chatModel = ChatModel.fromJson({
'username': 'Alex2020',
'name': 'Alex',
'lastName': 'Dunlop',
'icon': 'person.svg',
'time': '12:22',
'lastMessage': 'Some message texts here.'
});
final SharedPreferences prefs = await SharedPreferences.getInstance();
bool result = await prefs.setString('userChat', jsonEncode(chatModel));
print(result);
}
//For getting dta from shared preferences
Future<ChatModel> getChatModelInfo() async {
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
Map<String, dynamic> chatMap = {};
final String? userChatModelStr = sharedPreferences.getString('userChat');
if (userChatModelStr != null) {
chatMap = jsonDecode(userChatModelStr) as Map<String, dynamic>;
}
final ChatModel chatModel = ChatModel.fromJson(chatMap);
print(chatModel);
return chatModel;
}
我的问题是我只能保存一个JSON对象,但我需要保存一个对象数组。例如,我想保存以下JSON:
[
{
'username': 'Alex2020',
'name': 'Alex',
'lastName': 'Dunlop',
'icon': 'person.svg',
'time': '12:22',
'lastMessage': 'Some texts here.'
},
{
'username': 'Amanda20',
'name': 'Amanda',
'lastName': 'ALba',
'icon': 'person.svg',
'time': '1:29',
'lastMessage': 'Some other texts here.'
}
.
.
.
]
1条答案
按热度按时间7gcisfzg1#
然后可以将编码后的JSON
String
保存到List<String>
中,然后检索
List<String>
,这是一个已编码Json的列表,然后对其进行迭代,并对每个Json进行解码,这样您将得到一个List<Map<String, dynamic>>
以下是如何使用共享首选项执行此操作的示例: