该方法在 null 错误 flutter Hive 上被调用

问题描述

开箱

var savedList;

Future initiateHive() async {
    ///Creating a HiveBox to Store data
    savedList = await Hive.openBox('MusicBox');
}

将数据放入hive的函数

var songFav = SongPlayList()..songInfo = songs[currentIndex].id;

print(songs[currentIndex].id);

savedList.put(songs[currentIndex].id,songFav);

错误

抛出另一个异常:NoSuchMethodError: The method 'put' was 调用 null。

解决方法

我认为问题在于 savedList.put(songs[currentIndex].id,songFav);initiateHive() 完成执行之前被调用,因为 initiateHive() 是异步的,所以 savedList 仍然为 null

您可以执行以下操作:

if (savedList != null){
    savedList.put(songs[currentIndex].id,songFav);
}