Ovidiu Uşvat
Ovidiu Uşvat

Reputation: 823

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!

Upvotes: 14

Views: 18256

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 267614

There are two ways, you can do it.

  1. Use async-await:

    void func() async {
      bool value = await _getPref();
      setState(() {
        _value = value;
      });
    }
    
  2. Use then

    void func() {
      _getPref().then((value) {
        setState(() {
          _value = value;
        });
      });
    }
    

Upvotes: 2

JideGuru
JideGuru

Reputation: 7660

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

Upvotes: 13

Related Questions