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

Issue

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

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.
  final Block? block = blocks?.first;

  // you are sure blocks variable is initialized.
  // block is not nullable.
  final Block block = blocks!.first;

Answered By – Hamed

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.