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

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

我正在尝试阅读 shared preferences 但我卡住了。我有这个错误,我不知道如何处理它: A value of type 'Future<bool>' can't be assigned to a variable of type 'bool'

我的代码如下所示:

onTap: () {
        setState(() {
          if (_getPref()) {       //here occurs the error
            _stateColor = _disableColor;
            _setPref(false);
          } else {
            _stateColor = _enableColor;
            _setPref(true);
          }
        });
      },

以及方法:

Future<bool> _getPref() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool value = prefs.getBool(widget.myIndex) ?? false;
    return value;
  }

如果有人能帮助我,我将不胜感激!

你必须 await _getPref() 函数因为它 returns 一个未来 Future<bool>

onTap: () async {
    if (await _getPref()) {       //here occurs the error
      _stateColor = _disableColor;
      _setPref(false);
    } else {
      _stateColor = _enableColor;
      _setPref(true);
    }
    setState(() {});
  },

有两种方法,你可以做到。

  1. 使用async-await:

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

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