I am trying to read from shared preferences
but i got stuck. I've got this error and I don't know how to deal with it:
A value of type 'Future<bool>' can't be assigned to a variable of type 'bool'
My code looks like this:
onTap: () {
setState(() {
if (_getPref()) { //here occurs the error
_stateColor = _disableColor;
_setPref(false);
} else {
_stateColor = _enableColor;
_setPref(true);
}
});
},
And the method:
Future<bool> _getPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool value = prefs.getBool(widget.myIndex) ?? false;
return value;
}
I would by grateful if someone would help me!
You have to await
the _getPref()
function because it returns a future Future<bool>
onTap: () async {
if (await _getPref()) { //here occurs the error
_stateColor = _disableColor;
_setPref(false);
} else {
_stateColor = _enableColor;
_setPref(true);
}
setState(() {});
},
There are two ways, you can do it.
Use async-await
:
void func() async {
bool value = await _getPref();
setState(() {
_value = value;
});
}
Use then
void func() {
_getPref().then((value) {
setState(() {
_value = value;
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With