Mastering Null-aware Operators in Dart: Safely Handling Null Values
Improve code safety and readability by efficiently dealing with null values in your Dart applications.
Learn how to effectively handle null values in Dart using null-aware operators, including
- null-aware access (?.),
- null-aware assignment (??=),
- null-aware cascade (..), and
- null-aware conditional (??).
..
Null-aware access operator (?.):
It is used to access properties or call methods on an object that may be null. If the object is null, the expression returns null without throwing an exception.
class Person {
String name;
Person(this.name);
void sayHello() {
print('Hello, $name!');
}
}
void main() {
Person? person; // Nullable Person object
person?.sayHello(); // This will not throw an exception because of the null-aware access operator
}
..
Null-aware assignment operator (??=):
This operator assigns a value to a variable only if the variable is currently null. It is a handy way to set default values for nullable variables.
void main() {
int? num; // Nullable integer
int defaultValue = 42;
num ??= defaultValue; // Assigns the defaultValue to num only if num is null
print(num); // Output: 42
num ??= 10; // Since num is not null, it keeps the current value (42)
print(num); // Output: 42
}
..
Null-aware cascade operator (..):
It allows chaining multiple method calls on an object while ensuring the object is not null at each step. If the object is null, the cascade operation is skipped.
class Person {
String name;
Person(this.name);
void sayHello() {
print('Hello, $name!');
}
void introduce() {
print('I am $name.');
}
}
void main() {
Person? person; // Nullable Person object
person?.sayHello(); // This will not throw an exception because of the null-aware access operator
person?.introduce(); // This will also not throw an exception because of the null-aware access operator
// With the null-aware cascade operator, the chained method calls won't be executed if the object is null
person?
..sayHello()
..introduce();
}
..
Null-aware conditional operator (??):
This operator provides a default value when encountering a null value. It evaluates the expression on its left-hand side and returns it if it's non-null. Otherwise, it returns the expression on its right-hand side.
void main() {
int? number; // Nullable integer
int alternativeValue = 10;
int result = number ?? alternativeValue; // If number is null, result will be assigned the value of alternativeValue
print(result); // Output: 10
number = 5; // Now number is not null
result = number ?? alternativeValue; // Since number is not null, result will be assigned the value of number
print(result); // Output: 5
}
..
Comments
Post a Comment