Dart nullable, if-null, and assertion operator

Not null-able

If we annotate a type to be say, int, it means it can only be an integer. It cannot be null.

We can’t add two numbers if one of them is null:

Nullable (?)

If you want that int to be null, use the question mark to denote that.

With nullable, we get Compile Time Error.
This makes us write safer programs.

Assertion Operator (!)

If you’re sure that a nullable variable will ALWAYS have non-nullable values,
it’s safe to assign it to a non-nullable variable with the ! operator.

However, if you’re wrong, you’ll get a runtime error!

if-null operator (??)

In the example, x is -1, and thus maybeValue will be null;

Usually, we’d write it like this:

Now, we can use if-null operator like so:

Null Safety with type safety

So if x is -1, then maybeValue is left with null.
That’s not very good for future usage and printing.

So we can use a Type safety where if maybeValue is null, then we assign it to a default number.
Its a shorthand for if-null

Conditional Access Operator

Say we declare an array, and its of type String?.

in order to fix this, we use conditional access operator: