Dart analyzer not catching incompatible types when using null-coalescing operator

67 views Asked by At

I have the following code in a Flutter app that is currently running in unsound null safety mode (i.e. having both null-safe files and non-null-safe files).

int i = null;
String s = '';
double d = i ?? s;

This is obviously not correct, yet the Dart analyzer does not complain and the code compiles.

If I change the last line to

double d = null ?? s;

I get the expected error.

Shouldn't the Dart analyzer catch the error even when running in unsound null safety mode?

I have tried restarting the Dart analysis server, etc.

flutter doctor --verbose
[✓] Flutter (Channel stable, 2.10.2, on macOS 13.5.2 22G91 darwin-arm, locale en-SE)
    • Flutter version 2.10.2 at /Users/username/fvm/versions/2.10.2
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 097d3313d8 (1 year, 8 months ago), 2022-02-18 19:33:08 -0600
    • Engine revision a83ed0e5e3
    • Dart version 2.16.1
    • DevTools version 2.9.2
1

There are 1 answers

2
jamesdlin On BEST ANSWER

When you do:

double d = i ?? s;

the result of i ?? s is the nearest common base type of i and s, which is Object. Object then is implicitly downcast to double, which, despite being potentially unsafe, was allowed by default in the days before null-safety.

You can disallow implicit casts by setting strict-casts: true (or implicit-casts: false prior to Dart 2.16) in your analysis_options.yaml file, and then you will get a static analysis error:

error • A value of type 'Object' can't be assigned to a variable of type 'double'. • lib/foo.dart:4:14 • invalid_assignment