【问题标题】:How to save a list to shared preferences如何将列表保存到共享首选项
【发布时间】:2022-01-15 10:13:18
【问题描述】:

我想将列表保存到共享首选项,但它不起作用...目标是将数据添加到变量并保存。

这是我要保存的变量:

    var savedData = [
      {'date': 0, 'testNumber': 0},
    ];

这是我尝试保存和接收变量的代码:

 Future<void> saveDataTest() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList(
        'dataTest', savedData.map((i) => i.toString()).toList());
  }
    
 Future<String> getDataStringTest() async {
    final prefs = await SharedPreferences.getInstance();
    savedData =
     prefs.getStringList('dataTest').map((i) => int.parse(i)).toList();
    setState(() {});
  }

这是我得到的错误:

A value of type 'List<int>' can't be assigned to a variable of type 'List<Map<String, int>>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Map<String, int>>'.

【问题讨论】:

  • 您没有存储int 的列表。您存储了Map&lt;String, int&gt; 的列表。所以(i) =&gt; int.parse(i) 会是个问题。
  • 好的,谢谢!而这个问题的解决方法是什么?
  • 我不准备运行代码来确定。你可以试试(i) =&gt; Map&lt;String, int&gt;.from(i)
  • 当我尝试你的代码时,我得到了这个错误:参数类型'String'不能分配给参数类型'Map'
  • savedData是什么类型的变量?

标签: flutter dart sharedpreferences


【解决方案1】:

尝试使用来自import 'dart:convert';jsonEncodejsonDecode

像这样:


 Future<void> saveDataTest() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString("dataTest ", jsonEncode(savedData));
  }
    
 Future<String> getDataStringTest() async {
    final prefs = await SharedPreferences.getInstance();
    savedData = List.from(jsonDecode(prefs.getString("dataTest")));
    setState(() {});
  }

【讨论】:

  • 谢谢,但是当我尝试这个时,我得到了这个错误:_TypeError (type 'List' is not a subtype of type 'String')
  • 当我尝试获取数据时
  • 我已经更新了我的答案,试试吧。
  • 擦除应用程序的存储空间以清除首选项或以编程方式删除首选项。然后运行这段代码,看看它是否有效。
  • 现在我收到此错误:发生异常。 NoSuchMethodError(NoSuchMethodError:在 null 上调用了 getter 'length'。接收方:null 尝试调用:length)
【解决方案2】:

当您在列表中使用原始类型的 Map 对象时,您可以使用 jsonEncode 并转换为可以保存在 sharedPreferences 中的字符串,并在想要还原时使用 jsonDecoder

像这样:

String toBeSaved = jsonEncode(savedData);
prefs.setString('dataTest', toBeSaved);

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2011-12-18
    • 2017-04-26
    • 2021-05-31
    • 2014-01-11
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多