【问题标题】:How do I solve the 'Failed assertion: boolean expression must not be null' exception in Flutter如何解决 Flutter 中的“断言失败:布尔表达式不得为空”异常
【发布时间】:2018-06-26 22:57:24
【问题描述】:

我正在开发 Flutter 应用程序,并在 logcat 中不断收到此错误字符串。

Failed assertion: boolean expression must not be null

这里是有问题的代码:

@override
Widget build(BuildContext context) {
    return Center(
        child: ListView(
            children: <Widget>[
                TextField(
                    controller: controller,
                    decoration: InputDecoration(
                        hintText: "Type in something..."
                    ),
                ),
                RaisedButton(
                    child: Text("Submit"),
                    onPressed: () => addString(),
                ),
                Flex(
                    direction: Axis.vertical,
                    children: (list_two = null) ? [] :
                    list_two.map((String s) => Text(s)).toList() 
                )
            ],
        ),
    );
}

导致问题的原因是什么?

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    解决方案很简单,这里是这一行:

                Flex(
                    ...
                    children: (list_two = null) ? [] :
                    ...
                )
    

    需要让子项比较为布尔值,这需要 2 个等号。

                Flex(
                    ...
                    children: (list_two == null) ? [] :
                    ...
                )
    

    在使用 Android Studio 并使用 Java 编写时,这通常会引发编译器错误并且无法运行,但在使用 Flutter 插件编写 dart 时(截至今天,2018 年 6 月 26 日为 1.0) 没有显示编译器错误,而是看到了运行时错误。

    【讨论】:

    • 这里的问题是表达式的类型可以赋值给bool,因为在 Dart 中,甚至布尔值也是对象,因此可以为空。
    • 是的,虽然我预计很多从 Android 开发过来的人会遇到同样的问题,因为在使用 intellij 时寻找编译器错误是第二天性,而没有看到它们可能会导致开发人员忽略它,因为一个可能的问题。
    • 但是这个解决方案对我不起作用。但请确保初始化您正在比较的任何内容。例如 if( a == true ) 在这种情况下总是用 true 或 false 初始化 a ...否则可能 a 永远不会被分配并且应用程序会中断。
    • 为避免此类错误,请使用Yoda Conditions
    【解决方案2】:

    当您定义的布尔类型变量之一未使用默认值初始化,并且您尝试在某处使用并将其分配为值时,就会出现此问题。例如,也许你有你bool isEnabled ;未定义为应bool isEnabled = false;或bool isEnabled = true;你试着像readOnly: isEnabled,一样使用它

    为避免这些情况,请确保 isEnabled 不会是 null。这是我们如何避免这些的一种示例

    bool isChecked = false;
    
    Checkbox(
      value: isChecked,  // initialized with `true/false` also avoids the error,
      onChanged ...
    )
    

    【讨论】:

    【解决方案3】:

    这个错误通常是由使用 = 运算符检查布尔变量时引起的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-06
      • 2020-11-02
      • 2021-01-18
      • 2020-07-05
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多