如何解决在 SharedPreferences 和对象解码上颤动“NoSuchMethodErrorNoSuchMethodError: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();
}
//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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。