Home > Net >  How to save an array of JSON to the SharedPreferences in Flutter?
How to save an array of JSON to the SharedPreferences in Flutter?

Time:12-09

I'm working on a chat app in my Flutter project. I want to save the chat info coming from API to the SharedPreferences. I use the following model:

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

I use the following codes to write/read SharedPreferences data:

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

My problem is that I can only save one JSON object but I need to save an array of objects. For example, I want to save the following 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.'
    }
    .
    .
    .
]

CodePudding user response:

Then you can save the encoded JSON String in a List<String> to your shared preference instance,

Then retrieve that List<String> which is a list of encoded Json, then iterate over it and decode each one so you will have a List<Map<String, dynamic>>

this is a sample of how to do it with shared preferences:

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