How can I store and safe a List of Maps in Flutter using Shared Preferences? (Flutter, SharedPreferences)

Viewed 1129

I am trying to safe and load a conversation in my Flutter app. For that I push each message to a List of Maps:

  List<Map> messages = [];

  [...]

  messages.insert(0, {"data": 1, "message": "Hello, how are you?"}); //Message from user 1
  messages.insert(0, {"data": 2, "message": "I am fine."}); //Message from user 2

Now, how can I safe this data (the messages List) on the local device and load it when starting the app?

I have tried Shared Preferences already but it only allows me to store Lists of type String, not Map.

Can I convert List of type Map to List of type String and then work with it?

2 Answers

EDIT ! SharedPreferences stores only data of type:

  • String
  • bool
  • double

In this typical case you'll use the SharedPreferences to store a String type. To achieve this you'll need to generate a String type from your data.So you will convert a List => String. To do that here is a very short piece of code that you'll add it to generate your String .

List<Map> myData = [map2,map1];
jsonEncode(myData);

The idea is to transform your List into Json data so you can store it as String and decode it whene you need it.

I found this article: How to convert map to string?

This is my solution: I have a class with all my Shared Preferences functions. Now, when there is a message added to the List of Maps I then call a setMessages function which converts each Map in this List to a String. This String is added to a new List of Strings. Then this List of Strings is stored with Shared Preferences.

On initState I call a function to get the List of Strings with Shared Preferences. For each element in this list I convert the String to a Map. This Map is added to a List of Maps and then gets returned at the end so the listview can work with it.

Here is my code:

  static Future setMessages(List<Map> messages) async {
    List<String> messagesString = [];
    messages.forEach((element) {
      messagesString.add(json.encode(element));
    });
    await _preferences.setStringList(_keyUsername, messagesString);
  }

  static List<Map> getMessages() {
    List<String> messagesString =
        _preferences.getStringList(_keyUsername) ?? [];
    List<Map> messages = [];
    if (messagesString.isNotEmpty) {
      messagesString.forEach((element) {
        messages.add(json.decode(element));
      });
    }
    return messages;
  }

The json.encode and json.decode solved my problem. I also considered to work with sqflite and setup a local database like @Mol0ko suggested but in my case it's only this little data which makes this solution for saving and loading chat messages easier for me.

Related