【问题标题】:Flutter: Unhandled Exception: type 'String' is not a subtype of type 'bool'Flutter:未处理的异常:“String”类型不是“bool”类型的子类型
【发布时间】:2020-04-12 00:49:22
【问题描述】:

声明:

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);

【问题讨论】:

    标签: flutter


    【解决方案1】:
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool switchVariable = (prefs.getBool('switchVariable') ?? true);
    

    尝试在switchVariable前面添加bool

    SharedPreferences 的工作代码 n-p:

    @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,
                          ),
    

    【讨论】:

    • 谢谢,NXS。当我在有问题的行前添加“bool”时,出现逻辑错误,因为 switchVariable 在开始时已被声明为 bool。它需要保持一个全局变量,因为它在不同的模块中被访问。我不能像这样再次声明它。感谢您的意见。
    • 另外,我有数百行这样的代码使用共享首选项,以前完全没有任何问题。如果我每次想要使用共享偏好时都必须编写整个应用程序,那么就没有理由使用共享偏好。我应该能够获取实例、getValues、setValues。它一直是这样工作的,每个需求的单行代码。只是现在,除了更新 Flutter 和 shared-preferences 插件之外没有任何变化,它似乎已经破坏了逻辑。
    • @Bisclavret 如果您希望在不同的模块中访问它,您应该将其定义为“静态”。哦,好吧,所以它也可能只是更新......好吧,我不是专家,但我希望你能解决它!
    猜你喜欢
    • 1970-01-01
    • 2022-06-30
    • 2021-10-19
    • 2020-04-19
    • 2021-10-11
    • 2021-08-15
    • 1970-01-01
    • 2023-01-27
    • 2021-09-07
    相关资源
    最近更新 更多