Dart Null's
Null's in Dart
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 RUNTIME
when
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.
After 2.12
, this is no longer possible to do.
String impossible = null;
Conditional Operator (?.)
Now, after 2.12
we get an compile
time error that says something like:
The property
length
can’t be uncoditionally accessed because the receiver can benull
.
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 .lenght
method.
In this case the result would be null
printed.
If there was something inside possible:
TIP:
String? possible = null; // Both lines are the same
String? possible; // Both lines are the same
Best approach
String? possible = 'DARTH';
print(possible?.length); // 5
This would print 5
.
Bang Operator (!)
You can also use the !
(BANG) operator in these situations.
By using !
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
.