在 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();
}

下面是 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();

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)