Analyzer is missing an error case for “if (null)”

Consider the following:

final String foo = null;

void main()  {
  if(foo?.isNotEmpty){
    print("true");
  } else {
    print("not true");
  }
}

Even though this executes and prints not true, there is a compiler warning that states:

The value of the '?.' operator can be 'null', which isn't appropriate in a condition.

However, if we change it to explicitly null, there is no warning!

void main()  {
  if(null){
    print("true");
  } else {
    print("not true");
  }
}

I would argue that if(foo?.isNotEmpty) should not produce a compiler warning since the conditional checks if the value is true. It doesn’t check if the value is not false.

A common developer solution to this problem seems to be the following:

final String foo = null;

void main()  {
  if(foo?.isNotEmpty ?? false){
    print("true");
  } else {
    print("not true");
  }
}

I think this little lint/warning promotes codegolf when it could silently fail without issue.

Author: Fantashit

1 thought on “Analyzer is missing an error case for “if (null)”

  1. I added a reference to this issue in #34147, such that this known dart2js bug and a couple of similar ones aren’t forgotten due to the ‘area-analyzer’ label here.

Comments are closed.