What is NULL?
Null is a universal non value indicator that a specific variable does not hold something.
Up to version 2.12, you could assign anything to be null.
Before 2.12 The type of errors that come from using nulls, is that if you try to use to get for example the length of the string while it’s null will cause problems.
String possible = null; possible.lengh; // THIS WOULD CAUSE BIG PROBLEMS, THROWS ERROR
The worst part of this errors is that they will only happen at
the user is using them. And we want as much has possible for errors to be at
COMPILE time, so that we can fix them before reaching the users hands.
2.12, this is no longer possible to do.
String impossible = null;
Conditional Operator (?.)
2.12 we get an
compile time error that says something like:
lengthcan’t be uncoditionally accessed because the receiver can be
To avoid this, one of the ways is to use the Conditional Operator
String? possible = null; // <-- its optional, null print(possible?.length); // <-- is is not null access .length
We defined the variable has OPTIONAL/NULL using the
String? and when we want
to use it we say if there is something other than
null use its
In this case the result would be
If there was something inside possible:
String? possible = null; // Both lines are the same String? possible; // Both lines are the same
String? possible = 'DARTH'; print(possible?.length); // 5
This would print
Bang Operator (!)
You can also use the
! (BANG) operator in these situations.
! youre saying to the runtime,
TRUST ME, I KNOW WHAT I'M DOING.
String? possible = null; print(possible!.length); // ERROR
This will throw an error:
Null check operator used on a null value.