如何将JSON数组保存到Flutter的SharedPreferences中?

bhmjp9jg  于 2022-12-14  发布在  Flutter
关注(0)|答案(1)|浏览(202)

我正在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.'
    }
    .
    .
    .
]
7gcisfzg

7gcisfzg1#

然后可以将编码后的JSONString保存到List<String>中,
然后检索List<String>,这是一个已编码Json的列表,然后对其进行迭代,并对每个Json进行解码,这样您将得到一个List<Map<String, dynamic>>
以下是如何使用共享首选项执行此操作的示例:

import "dart:convert";

void main() async {
   final SharedPreferences sharedPreferences =
        await SharedPreferences.getInstance();
  
  List<Map<String, String>> list = [
    {
      '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.'
    }
  ];
  String key = "encodedElementskey";
  
  await saveToSharedPrefs(list, key);
  
  print(await getFromSharedPrefs(key));
}

void saveToSharedPrefs(List<Map<String, dynamic>> list, String key) async {
  List<String> encodedElems = [];

  list.forEach((element) {
    encodedElems.add(jsonEncode(element));
  });
     await prefs.setStringList(key, encodedElems);

}
List<Map<String, dynamic>> getFromSharedPrefs(String key) {
        List<String> list = await prefs.getStringList(key);
  List<Map<String, dynamic>> decodedElements = [];

  list.forEach((element) {
    decodedElements.add(jsonDecode(element));
  });
  return decodedElements;
}

相关问题