Ostap Filipenko
Ostap Filipenko

Reputation: 239

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

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();

Upvotes: 1

Views: 1444

Answers (1)

Alok
Alok

Reputation: 8978

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. :)

Upvotes: 2

Related Questions