Null-Aware Operators (??, ?, ??=) in Dart Programming

Flutter Jun 25, 2024

In Dart programming language, null-aware operators are a set of operators that allow you to perform certain operations on variables that may or may not contain a null value.

These operators allow you to write code that can safely handle null values without having to constantly check for null values using if statements or the ?? operator.

There are three null-aware operators in Dart:

?. (null-aware property access):

This operator is used to access a property of an object, but only if the object is not null. If the object is null, the expression returns null instead of throwing a NullPointerException.

For example:

String? name;
print(name?.length);  // Prints `null`

name = 'nepal';
print(name?.length);  // Prints `5`

?? (null-aware coalescing):

This operator is used to provide a default value for a variable that may be null. If the variable is not null, the operator returns the value of the variable. If the variable is null, the operator returns the default value.

For example:

String? name;
print(name ?? 'Default name');  // Prints 'Default name'

name = 'Nepal';
print(name ?? 'Default name');  // Prints 'Nepal'

??= (null-aware assignment):

This operator is used to assign a value to a variable, but only if the variable is null. If the variable is not null, the operator does nothing.

For example:

String? name;
name ??= 'Default name';  // name is now 'Default name'
print(name);
name = 'Nepal';
name ??= 'Default name';  // name is still 'Nepal'
print(name);

These null-aware operators can be useful for writing code that is more concise and easier to read, as they allow you to avoid repetitive if statements or the use of the ?? operator multiple times in a row.

However, it's important to use these operators wisely, as they can also make code more difficult to understand if used excessively or in an unclear way.

Tags