Search code examples
fluttersharedpreferences

Flutter Error: A value of type 'Future<bool>' can't be assigned to a variable of type 'bool'


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!


Solution

  • 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(() {});
      },