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
The three null-aware operators that Dart provides are ?. , ?? , and ??= .
For us, in the context of null safety, that means that if an expression has a static type that does not permit null , then no possible execution of that expression can ever evaluate to null . The language provides this guarantee mostly through static checks, but there can be some runtime checks involved too.
The Dart language now supports sound null safety! When you opt into null safety, types in your code are non-nullable by default, meaning that variables can't contain null unless you say they can. With null safety, your runtime null-dereference errors turn into edit-time analysis errors.
Non-nullable By Default: By default, Dart variables aren’t nullable unless you explicitly specify that they can be null. This is because non-null was by far the most common option in API research. Incrementally Adoptable: Migration to null safety is completely up to you. You can choose what to migrate to null safety, and when.
Your Dart program has a whole universe of types in it: primitive types like intand String, collection types like List, and all of the classes and types you and the packages you use define. Before null safety, the static type system allowed the value nullto flow into expressions of any of those types.
Before null safety, Objectwas Dart’s top type and Nullwas its bottom type. Since Objectis non-nullable now, it is no longer a top type. Nullis not a subtype of it.
The null-aware operator is a nice tool for making nullable types usable in Dart. While we can’t let you call methods on nullable types, we can and do let you use null-aware operators on them. The post-null safety version of the program is: // Using null safety:String?notAString=null;print(notAString?.length); It works just like the previous one.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With