如何解决 Flutter 中的“失败断言:布尔表达式不能为空”异常

Sil*_*los 14 dart flutter

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

Failed assertion: boolean expression must not be null
Run Code Online (Sandbox Code Playgroud)

这是有问题的代码:

@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() 
                )
            ],
        ),
    );
}
Run Code Online (Sandbox Code Playgroud)

导致问题的原因是什么?

Sil*_*los 14

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

            Flex(
                ...
                children: (list_two = null) ? [] :
                ...
            )
Run Code Online (Sandbox Code Playgroud)

需要让孩子比较是一个布尔值,这需要 2 个等号。

            Flex(
                ...
                children: (list_two == null) ? [] :
                ...
            )
Run Code Online (Sandbox Code Playgroud)

在使用 Android studio 并用 Java 编写时,这通常会引发编译器错误并且不会运行,但是在使用 Flutter 插件(截至今天的 1.0,2018-06-26)用 dart 编写时没有显示编译器错误,我们改为看到运行时错误。

  • 这里的问题是表达式的类型可以与 `bool` 关联,因为在 Dart 中,即使是布尔值也是对象,因此可以为空。 (2认同)