首页 > 解决方案 > 在 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();

标签: flutterdartserializationsharedpreferencesdecode

解决方案


推荐阅读