15

I was working on a Flutter application and kept receiving this error String in the logcat.

Failed assertion: boolean expression must not be null

Here is the code in question:

@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() 
                )
            ],
        ),
    );
}

What is causing the problem?

PGMacDesign
  • 6,092
  • 8
  • 41
  • 78

2 Answers2

16

The solution was a simple one, this line here:

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

Needed to have the children comparison be a boolean, which requires 2 equals signs.

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

While using Android studio and writing in Java, this would normally throw a compiler error and not run, but while writing in dart with the Flutter plugin (1.0 as of today, 2018-06-26) no compiler error is shown and we instead see a runtime error.

PGMacDesign
  • 6,092
  • 8
  • 41
  • 78
  • 2
    The issue here is that the type of the expression is assingable to `bool` because in Dart, even booleans are objects and therefore nullable. – lrn Jun 27 '18 at 06:03
  • Yup, though I expect quite a few people coming over from Android development will have the same issue as looking for compiler errors is second nature while using intellij and not seeing them may cause a dev to ignore it as a possible problem. – PGMacDesign Jun 27 '18 at 13:41
  • However this solution didn't worked for me. but make sure you initialize whatever you are comparing. for example if( a == true ) in that case always initialize a with true or false ... else may be possible that a never get assign and app will break. – Akram Chauhan Jun 11 '19 at 07:11
  • 1
    To avoid errors like these use [Yoda Conditions](https://en.wikipedia.org/wiki/Yoda_conditions). – Seriously Mar 29 '20 at 12:53
0

this error often caused by when a bool variable is checked using = operator