我收到错误“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();