In Dart, there are several ways to perform null checks to handle situations where a variable might be null.
Conditional Operator
The conditional operator (
?
) can be used for concise null checks.You have a variable called
someNullableVariable
, and you want to check if it's not null.The part before the
?
(someNullableVariable != null
) is the condition. It checks ifsomeNullableVariable
has a value (is not null).If the condition is true (meaning
someNullableVariable
is not null), then the value before the:
(colon) is assigned to the variableresult
. So,result
becomessomeNullableVariable
.If the condition is false (meaning
someNullableVariable
is null), then the value after the:
is assigned toresult
. So,result
becomesdefaultValue
.
var result = sumNullableVariable != null ? someNullableVariable : defaultValue;
Conditional Access (?.) and Cascade (..) Operators
?.
Imagine you have an object called someObject
, and you want to access a property or call a method on it, like length
. However, there's a chance that someObject
could be null. To avoid potential errors in this situation, you can use the conditional access operator (?.
).
var length = someObject?.length;
If
someObject
is not null, it will access thelength
property.If
someObject
is null, it will not try to accesslength
, and the result (length
variable in this case) will also be null.
..
The cascade operator (..) allows you to call multiple methods or perform multiple actions on an object without having to repeat the object's name.
dartCopy codesomeObject
..method1()
..method2();
Is like saying: "On someObject
, do method1
, then do method2
." It's a concise way to perform a sequence of actions on the same object without having to repeat the object's name.
If-Null Operator(??=)
Imagine you have a variable called someNullableVariable
, and you want to assign it a default value (defaultValue
) only if it currently has no value (i.e., it's null). The if-null operator (??=
) helps you achieve this in a concise way.
someNullableVariable ??= defaultValue;
If
someNullableVariable
is not null, it remains unchanged.If
someNullableVariable
is null, it gets assigned the value ofdefaultValue
.
This operator is handy for situations where you want to provide a default value to a variable only if it hasn't been assigned a value yet. It helps ensure that the variable is never null after this operation.