如何在 Flutter 中使用 SharedPreferences 保存 List<List<String>>
How to save List<List<String>> with SharedPreferences in Flutter
我正在尝试保存一个列表列表,但我不知道该怎么做。
所以我有 List _randList = new List();
看,我们无法在订单商店 List<List<String>>
中使用 Shared Preferences。但是,我们始终可以使用变通方法。
因为我们已经知道我们只能在共享首选项中存储 List<String>
,所以最好 以字符串 的形式存储嵌套列表,例如以下
List<String> _arr = ["['a', 'b', 'c'], ['d', 'e', 'f']"];
这样,您将只有一个 List<String>
,但也会有您的数组,您可以以任何形式提取这些数组,或者只是下面的示例
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']]
这样,您就可以将数据存储在您的共享首选项中
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");
}
因此,您的要点是 将嵌套数组存储到单个字符串中,我想您可以开始了。 :)
我正在尝试保存一个列表列表,但我不知道该怎么做。
所以我有 List _randList = new List();
看,我们无法在订单商店 List<List<String>>
中使用 Shared Preferences。但是,我们始终可以使用变通方法。
因为我们已经知道我们只能在共享首选项中存储 List<String>
,所以最好 以字符串 的形式存储嵌套列表,例如以下
List<String> _arr = ["['a', 'b', 'c'], ['d', 'e', 'f']"];
这样,您将只有一个 List<String>
,但也会有您的数组,您可以以任何形式提取这些数组,或者只是下面的示例
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']]
这样,您就可以将数据存储在您的共享首选项中
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");
}
因此,您的要点是 将嵌套数组存储到单个字符串中,我想您可以开始了。 :)