flutter - 在 SharedPreferences 和对象解码上颤振“NoSuchMethodError(NoSuchMethodError:getter 'length' was called on null” *仅限首次启动*
问题描述
我收到一个错误“NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null”。从我的调试中,我发现当代码转到 SharedPreferences.getInstance(); 它会导致这个问题,因为它然后转到对象解码代码并提示提到的错误。
这仅在应用程序首次启动时发生。重置应用程序后,它按预期工作。
下面收到的错误。
NoSuchMethodError (NoSuchMethodError: The getter 'length' was called on null.
Receiver: null
Tried calling: length)
下面是初始代码。
@override
void initState() {
print("Initialized");
intialKarak(); //debug trail, where the issue happens
initFunc();
_flareController = GlassLoadingController();
super.initState();
}
下面是 InitialKarak() 函数
//This function is required to intialize the list and avoid errors
void intialKarak() async {
// var txDate = DateTime.now();
// DateFormat('dd-MM-yyyy').format(txDate);
if (global.karakList.isEmpty) {
Karak initialKarak = new Karak(
/*txDate.add(Duration(days: 9999))*/ DateTime.now()
.add(Duration(days: 9999))
.toString(),
0);
global.karakList.add(initialKarak);
serialize(); //debug trail, where the issue happens
global.karakList.removeAt(0);
}
}
serialize() 函数问题出在哪里
void serialize() async {
final prefs = await SharedPreferences.getInstance(); //debug trail, where the issue happens
encodedData = Karak.encode(global.karakList);
prefs.setString('karakList', encodedData);
global.karakList = Karak.decode(encodedData);
for (var karak in global.karakList) {
print(karak.date + " and drunk " + karak.counter.toString());
}
}
解码对象函数如下
static List<Karak> decode(String karaks) =>
(json.decode(karaks) as List<dynamic>)
.map<Karak>((item) => Karak.fromJson(item))
.toList();
解决方案
推荐阅读
- django - 如何使用自定义 SQL 从 Django 模型管理器返回查询集而不是列表
- python - Lambda 错误:不支持“>” - 但未使用“>” - 将函数转换为 lambda
- java - 如何在 Spring Boot 中定义来自地址的邮件?
- integration - 如何将我的应用程序集成到 HL7 V2.5 医院 HIS?
- python-3.x - Bottle: HEAD 总是回退到 GET,因此函数总是执行两次?
- python - 正则表达式捕获第一个数字组
- compiler-errors - 如何使用 `real sepaa[allocatable](:)` 语法编译 Fortran?
- angular - 在可编辑材料表中使用 mat-checkbox 时出错
- string - Freemarker ISO字符串到带有时区的日期时间
- python - 2D 切片混乱