Search code examples
listflutterdarttype-conversionsharedpreferences

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


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?


Solution

  • 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.