【问题标题】:How to fix a nullable expression can't be used as a condition error如何修复可空表达式不能用作条件错误
【发布时间】:2022-01-20 01:30:00
【问题描述】:

下面的代码给了我一个错误:“rememberMe = newValue”的: “'bool 类型的值?'不能分配给 'bool' 类型的变量。”

但如果我将rememberMe 的声明更改为“bool?rememberMe = false;” 然后我在线上出现错误: “如果(记住我){”的: “不能为空的表达式不能用作条件。”

布尔值?还会在以下行中产生问题:“prefs.setBool('remember', rememberMe);”

  bool rememberMe = false;
  ...

  setRemberMeValue() async {
    await _getRememberUser();
    if (rememberMe) {
      usernameController.text = userName;
      passwordController.text = password;
      setState(() {
        rememberMe = rememberMe;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final userField = UserTextField(style: style, usernameController: usernameController);
    final passwordField = PasswordTextField(style: style, passwordController: passwordController);
    final rememberMeCheckbox = Checkbox(
      value: rememberMe,
      onChanged: (newValue) {
        setState(() {
          rememberMe = newValue;
        });
      },
    );

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    这是与Checkbox 的编写方式有关的问题,理论上一个复选框可以是“选中”、“未选中”或“否定选中”(用叉号代替选中),所以@987654322 @ 方法如果选中则返回 true,如果未选中则返回 false,如果选中则返回 null

    因为理论上它可能是null,所以你不能只将newValue 分配给rememberMe 但是,你的Checkbox 永远不会被否定检查,因为你没有告诉它,所以你可以当然newValue 不会是null,所以你可以这样做:

    rememberMe = newValue == true;
    

    这样,如果 newValue 为 null,null == true 将评估为 false。

    但是有更好的方法来做到这一点! 您可以使用空检查运算符 (!) 告诉 newValue 它永远不能为空:

    rememberMe = newValue!;
    

    这样,如果newValue 为空,我们会得到一个异常,但我们已经知道newValue 不为空!

    【讨论】:

    • 对于bool? 可能是null 的情况,您应该更喜欢newValue ?? false 而不是newValue == true,因为它更清楚地表明它打算处理null , 和 true/false 的布尔比较通常是代码异味。
    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 2012-06-02
    相关资源
    最近更新 更多