0

I just finished my nullsafe migration. I'm finding that wrapping code with a null check only sometimes removes the need for the nullcheck ! operator? E.g.,

class MyClass {
  double divideBy4(double numerator) {
    return numerator / 4;
  }

  double quarteredWorks(double? value) {
    if (value != null)
      return divideBy4(value); // <- no intellisense warning
    else
      return 0;
  }

  double quarteredDoesntWork(double? value) {
      return divideBy4(value); // <- intellisense: "double? can't be assigned to double"
  }

  double? value;

  double divideBy2() {
    if (value != null)
      return value / 2; // <- intellisense: "receiver can be null"
    else
      return .0;
  }
}

EDIT Changed my example to show an example of wrapping with a null check that works

buttonsrtoys
  • 2,359
  • 3
  • 32
  • 52
  • Your `value` can be null as it's defined `double?`. The null safety is here to avoid checking null values. Here, the check is not enough as the `value` var can be null. You can tell the compiler that you are sure the value is not null thanks to your manual check by using the `!` operator. Checking with an if statement does not override the nullability of the variable from its definition (it's just my understanding, I didn't thing a thing about that in the doc). – Maxouille Apr 29 '21 at 12:58
  • This might be related to Intellisense which does not infer the type correctly, by copy/pasting your code into DartPad with nullsafety enabled I don't have any warning. – Guillaume Roux Apr 29 '21 at 13:26
  • @Maxouille There are times where an if statement negates the need for the `!` operator. See https://www.youtube.com/watch?v=_VrulBiOV_o&t=15s at 6:02. I updated my example to show where sometimes it works and other times it doesn't? – buttonsrtoys Apr 29 '21 at 15:01
  • @GuillaumeRoux. Weird. When I pasted into DartPad I still get the warnings. – buttonsrtoys Apr 29 '21 at 15:03
  • 2
    https://stackoverflow.com/questions/65035574/null-check-doesnt-cause-type-promotion-in-dart – Nitrodon Apr 29 '21 at 15:32

0 Answers0