【问题标题】:Failed assertion: boolean expression must not be null flutter断言失败:布尔表达式不能为空颤动
【发布时间】:2021-02-15 22:25:09
【问题描述】:

我正在尝试获取开关状态,但它一直向我显示此错误 断言失败:布尔表达式不能为空

这就是我如何通过将开关状态保存到共享首选项并取回值来获得它

  bool availability;
  
  
  Future<bool> getSwitchState() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      availability = prefs.getBool('isAvailable') ??false;
    });
  }
  
  
 // and this how i save the switch state when it is changed 
  
  
   Future<bool> savingSwitchValue(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setBool('isAvailable', value);
  }
  
     CustomSwitch(
                  value: availability,
                  onChanged: (value) {
                    if (availability == false) {
                      setState(() {
                        availability = true;
                        savingSwitchValue(value);
                        print('this is true');
                        goOnline();
                        getLocationUpdates();
                      });
                    } else {
                      setState(() {
                        availability = false;
                        savingSwitchValue(value);
                        print('this is false');
                        goOffline();
                      });
                    }
                  },
                  activeColor: Colors.green,
                ),
我该如何解决这个问题

【问题讨论】:

    标签: android ios flutter mobile-application


    【解决方案1】:

    您应该在第一行代码中为可用性变量指定一个默认值。

    它出错了,因为您在为其赋值之前就使用了它。

    【讨论】:

    • 很好,但我之前已经尝试过,它显示另一个错误
    • 没有错误对不起..它没有从共享首选项中获取保存的值
    • 从共享偏好中读取是一个异步任务,所以你需要通过一些东西来初始化你的值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2020-11-02
    • 1970-01-01
    • 2020-04-23
    • 2021-01-18
    • 2020-07-05
    • 2021-07-09
    相关资源
    最近更新 更多