断言失败:布尔表达式不能为空颤振



我试图获得开关状态,但它一直显示我这个错误断言失败:布尔表达式不能为空

,这是我如何得到它通过保存开关状态为共享首选项,并获得值返回

bool availability;


Future<bool> getSwitchState() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
availability = prefs.getBool('isAvailable') ??false;
});
}


// and this how i save the switch state when it is changed 


Future<bool> savingSwitchValue(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setBool('isAvailable', value);
}

CustomSwitch(
value: availability,
onChanged: (value) {
if (availability == false) {
setState(() {
availability = true;
savingSwitchValue(value);
print('this is true');
goOnline();
getLocationUpdates();
});
} else {
setState(() {
availability = false;
savingSwitchValue(value);
print('this is false');
goOffline();
});
}
},
activeColor: Colors.green,
),
如何解决这个问题

您应该在第一行代码中使用默认值分配可用性变量。

它运行到错误,因为你在给它赋值之前使用它。

相关内容

最新更新