如何保存List< List< String>>在Flutter中使用SharedPreferences [英] How to save List<List<String>> with SharedPreferences in Flutter

查看:86
本文介绍了如何保存List< List< String>>在Flutter中使用SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保存列表列表,但我不知道该怎么做.所以我有List< List>_randList = new List();

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

推荐答案

请参阅,我们无法使用共享的首选项以存储 List< List< String>> .但是,我们总是可以使用一种解决方法.

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

因为我们已经可以只在共享首选项中存储 List< String> ,所以最好以字符串形式存储嵌套列表,像下面一样

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']"];

通过这种方式,您将仅具有 List< String> ,但也将具有数组,可以以任何形式或以下示例提取这些数组

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

这篇关于如何保存List&lt; List&lt; String&gt;&gt;在Flutter中使用SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆