flutterdartdart-null-safety

What's the differences between "!" and "?" operators in dart null safety?


Could anyone explain a little bit about the differences between using this:

final block = blocks?.first;

and this:

final block = blocks!.first;

where blocks is:

List<Block>? blocks

Solution

  • In short, the first line of code will return null if blocks is null and the second line will throw an exception if blocks is null.

    When you use blocks?.first, the value of blocks can be null, but when you use blocks!.first, you inform the compiler that you are certain that blocks are not null.

    final block = blocks!.first; means you are completely assured that List<Block>? blocks is initialized before block assignment.

    also in final block = blocks?.first;, block will be nullable, but in final block = blocks!.first;, block is not nullable.

      List<Block>? blocks;
      ...
      // you are not sure blocks variable is initialized or not.
      // block is nullable.
      // return null if blocks is null.
      final Block? block = blocks?.first;
    
      // you are sure blocks variable is initialized.
      // block is not nullable.
      // throw an error if blocks is null.
      final Block block = blocks!.first;