How to save List<List<String>> with SharedPreferences in Flutter

拜拜、爱过 提交于 2021-02-10 14:53:17

问题


I am trying to save a List of List but I don't know how to do that. So I have List<List> _randList = new List();


回答1:


See, there is no way that we can use Shared Preferences in order store List<List<String>>. However, we can always use a workaround.

Since, we already that we can store the List<String> only in the Shared Preferences, it is best to store the nested lists in the form of String, like below

List<String> _arr = ["['a', 'b', 'c'], ['d', 'e', 'f']"];

In this way, you will be having a List<String> only, but would also have your arrays as well, you can extract those arrays out in any form, or just the example below

for(var item in _arr){
  print(item);
}

//or you want to access the data specifically then store in another array the item
var _anotherArr = [];
for(var item in _arr){
  _anotherArr.add(item);
}

print(_anotherArr); // [['a', 'b', 'c'], ['d', 'e', 'f']]

In this way, you will be able to store the data in your Shared Preferences

SharedPreferences prefs;
List<String> _arr = ["['a', 'b', 'c'], ['d', 'e', 'f']"];


Future<bool> _saveList() async {
  return await prefs.setStringList("key", _arr);
}

List<String> _getList() {
  return prefs.getStringList("key");
}

So, the take away for you is to store the nested arrays in to a single string, and I guess, you are good to go. :)



来源:https://stackoverflow.com/questions/62657223/how-to-save-listliststring-with-sharedpreferences-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!