【发布时间】: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<String, int>的列表。所以(i) => int.parse(i)会是个问题。 -
好的,谢谢!而这个问题的解决方法是什么?
-
我不准备运行代码来确定。你可以试试
(i) => Map<String, int>.from(i) -
当我尝试你的代码时,我得到了这个错误:参数类型'String'不能分配给参数类型'Map
' -
savedData是什么类型的变量?
标签: flutter dart sharedpreferences