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

The method was called on null error 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);

错误是

Another exception was thrown: NoSuchMethodError: The method 'put' was called on null.

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

你可以这样做:

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