Sermed mayi
Sermed mayi

Reputation: 757

Flutter : how save list of dynamic to shared preference

I am trying to save a list of data to shared preference and read these articles but don't works with me :

Flutter save List with shared preferences

Shared Preferences in Flutter cannot save and read List

I have this list :

var list =[
       {
          "id" : 1,
          "name" : "ali"
        },
        {
          "id" : 2,
          "name" : "jhon"
        }
      ];

I tried this :

setList() async {
    Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
    final SharedPreferences prefs = await _prefs;
    prefs.setStringList('list', list);
  }

I get this error : The argument type 'List<Map<String, Object>>' can't be assigned to the parameter type 'List<String>'

Upvotes: 0

Views: 883

Answers (1)

quoci
quoci

Reputation: 3557

The error occurs because your list is of type Map<String, Object> and not a String. To fix this you can use jsonEncode method which converts it into a String

Future<void> setList() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final List<String> jsonList = list.map((item) => jsonEncode(item)).toList();
  prefs.setStringList('list', jsonList);
}

If you now want to retrieve this list you have to use jsonDecode to convert it back to a Map<String, Object>.

List<Map<String, Object>> getList() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final List<String> jsonList = prefs.getStringList('list')
  final List<Map<String, Object> list = jsonList.map((item) => jsonDecode(item)).toList();
  return list;
}

Upvotes: 1

Related Questions