flutter - 如何使用共享首选项存储 3d 字符串数组
问题描述
我是 Flutter 的新手,正在做一些类似于日历的事情,其中所有用户创建的事件都存储在 3d arrayIventList[month][day][numOfIvent]
中。我正在尝试将数组编码为字符串,以便通过共享首选项保存它,然后在使用jsonEncode
andjsonDecode
方法接收数据时将其解码回来。但是在解码结果数组时,我得到error: The argument type 'String?' can't be assigned to the parameter type 'String'. (argument_type_not_assignable at [buzhigsr_app] lib \ calender.dart: 35)
. 也许有人知道如何解决这个错误或通过共享首选项保存数组?在此先感谢大家。
List tList = List.generate(12, (m) => List.generate(31, (d) => List.generate(40, (i) => "")));
getAndSendData() async{
var prefs = await SharedPreferences.getInstance();
prefs.setString('key', jsonEncode(tList));
tList = jsonDecode(prefs.getString('key'));
}
解决方案
prefs.setString('key', jsonEncode(tList)) 的类型是 String?。jsonDecode() 将 String 作为参数,所以当你给它 String? 时它会引发错误。您只需执行此操作即可检查它是否为空。
List<List<List<String>>> tList = List.generate(
12, (m) => List.generate(31, (d) => List.generate(40, (i) => "")));
getAndSendData() async {
var prefs = await SharedPreferences.getInstance();
prefs.setString('key', jsonEncode(tList));
final listString = prefs.getString('key');
if (listString != null) {
final decodedList = jsonDecode(listString);
if (listString != null) {
final decodedList = jsonDecode(listString);
final decodedTList = (decodedList as List)
.map((firstD) => (firstD as List)
.map((secondD) =>
(secondD as List).map((thirdD) => thirdD.toString()).toList())
.toList())
.toList();
tList = decodedTList;
}
}
推荐阅读
- mysql - 关于 mysql 的混淆,例如搜索和 = 搜索
- vue.js - vue.js如何组织前端数据(如产品信息)
- angular -
使 html 内容在 Angular 中消失 - javascript - 在加载实际的 html 文件之前加载另一个 html 文件作为弹出窗口
- javascript - 从restapi调用数据并在ui中解析成表
- php - 在 Api 后面构建 Web 应用程序功能
- apache-spark - 在 SparkStreaming 中停止 DirectStream 后如何保存数据以供以后处理?
- elasticsearch - 在 ElasticSearch 6 中使用带有过滤器的嵌套对象进行聚合
- javascript - 如何更改每个自定义范围步骤上的图标颜色
- django - ModelSerializer:包含模型的所有字段和所有属性