Flutter:未处理的异常:类型'String'不是类型'bool'的子类型

时间:2020-04-12 00:49:22

标签: flutter

声明:

bool switchVariable = true;

代码部分:

SharedPreferences prefs = await SharedPreferences.getInstance();
switchVariable = (prefs.getBool('switchVariable') ?? true);

错误:

Unhandled Exception: type 'String' is not a subtype of type 'bool'

当您选择有问题的代码的链接时,此错误将突出显示此错误:

*switchVariable* = (prefs.getBool('switchVariable') ?? true);

1 个答案:

答案 0 :(得分:0)

SharedPreferences prefs = await SharedPreferences.getInstance();
bool switchVariable = (prefs.getBool('switchVariable') ?? true);

尝试在switchVariable的前面添加布尔值

SharedPreferences的工作代码片段:

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    getSwitchValues();
  }

  bool _isSwitched;
    getSwitchValues() async {
        _isSwitched = await getSwitchState();

        setState(() {_isSwitched = _isSwitched});
      }  



//Gets initialized when the switch is switched
      Future<bool> saveSwitchState(bool value) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        //Set the bool value of switchState the switch
        prefs.setBool("switchState", value);
        print('Switch Value saved $value');

    return prefs.setBool("switchState", value);
  }

  Future<bool> getSwitchState() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Get's the value from prefs
    bool _isSwitched = prefs.getBool("switchState");
    print(_isSwitched);
    return _isSwitched;
  }

开关:

Switch(
                        value: _isSwitched ?? false,
                        onChanged: (bool value) {
                          setState(() {
                            _isSwitched = value;

                            saveSwitchState(value);
                            print('Saved state is $_isSwitched');

                          });
                        },
                        activeTrackColor: Colors.lightGreenAccent,
                        activeColor: Colors.green,
                      ),