Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 538
Ovidiu Uşvat Avatar asked Jun 16 '20 14:06

Ovidiu Uşvat


2 Answers

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(() {});
  },
like image 170
JideGuru Avatar answered Nov 19 '22 01:11

JideGuru


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;
        });
      });
    }
    
like image 28
CopsOnRoad Avatar answered Nov 19 '22 00:11

CopsOnRoad