Dart: non-nullable local variable initialized in if block fails with "must be assigned before it can be used"

Viewed 53

I'm using Dart 2.15.1 with default setting null safety enabled. I don't understand, why this does not work:

main() {
  int test;
  if (1 > 0) { test = 42; }
  print(test); // <- The non-nullable local variable 'test' must be assigned before it can be used.
}

while this works without any error:

main() {
  int test;
  if (true) { test = 42; }
  print(test); // <- no error here
}

It's not a big thing, I can certainly implement a workaround, but I'm curious why dart behaves like this.

Thank you for your help.

1 Answers

Dart infers some control flow at compile time, but only really for very simple boolean expressions, basically only literals.

The expression 0 < 1 is guaranteed to be true, but the language specification treats it as a run-time evaluated expression, the meaning of which cannot be known until after it has been evaluated, which means it has to be typed first, and flow analysis happens during the type analysis step. So, the if is treated in the flow analysis as a branch that can go either way.

Related