0

I recently run into some strange behavior when using double question mark. Here is the example code:

void main() {
  String strA;
  String strB;

  print('start');
  strB = strA ?? 5; // wrong use of default value type. It should be a String here.
  print('end');
}

The program never run to the end and even not throwing out any error message.

Is the behavior expected?

yellowgray
  • 4,006
  • 6
  • 28
  • First ,you should make your `strA` nullable using `String? strA`. Regardless, `A value of type 'Object' can't be assigned to a variable of type 'String'`. The program even won't compile. – iDecode Nov 07 '20 at 09:33
  • Actually it can compile without any error on my computer (tried on Android Studio and DartPad), only throw error message until runtime. – yellowgray Nov 07 '20 at 13:17
  • The main problem was happen when I tried to learn riverpod package from it's example(Todo https://github.com/rrousselGit/river_pod/tree/master/examples/todos), while I did a very dump mistake that write `id = id ?? _uuid.v4();` to `id = id ?? _uuid.v4;`. It took me a while debugging because it just pass this line without throwing any error message. – yellowgray Nov 07 '20 at 13:23
  • So I make a small reproducible code here. Thanks for the mysterious power, this simple example works as expected now. – yellowgray Nov 07 '20 at 13:24

1 Answers1

0

How you're running this code?

When I run it, I get this output:

▶ dart test.dart
start
Unhandled exception:
type 'int' is not a subtype of type 'String'
#0      main (file:///Users/renato/programming/projects/test.dart:6:3)

As I expected.

What Dart version are you using (run dart --version)? Make sure you have an up-to-date version like 2.10.

If you still have issues, you might have a local analysis_options.yaml file which overrides the Dart compiler checks to be more lenient, in which case it might not check the types (I am not sure which option would enable this, but I suppose it's possible).

Check how analysis options work here.

I suggest you always enable "strong mode" by adding this to your analysis options file:

analyzer:
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false

By the way, if you want to try the new Dart NNBD (Not-Null-By-Default) experimental feature, you need to use the Dart dev channel releases and run your program with dart --enable-experiment=non-nullable file.dart.

To learn how to enable NNBD, check the null-safety tech preview 2 blog post about it.

Renato
  • 12,940
  • 3
  • 54
  • 85
  • Strange thing that it did happen this morning in my Android Studio (Dart 2.11.0-213.1.beta (beta)) and DartPad online (Based on Flutter 1.23.0-18.1.pre Dart SDK 2.10.3). It now all print out the error message. Thank you. – yellowgray Nov 07 '20 at 13:15