What does double question mark (??) means in dart programming language?
The double question mark operator checks if the variable specified at the left of this operator is null or not. If the left side variable is null it will return its right side expression.
Let’s understand with an example:
void main() {
String? str1;
String str2 = str1 ?? "str1 variable is null";
print(str2);
}
Output:
str1 variable is null
Explanation:
Here the value of the variable str1
is null so at the time of assigning value to str2
the double question mark operator (??) checks its left side variable (str1
) is null or not. As the variable str1
is null it returns the right side string “str1 variable is null“.
void main() {
String? str1 = "Test String";
String str2 = str1 ?? "str1 variable is null";
print(str2);
}
Output:
Test String
Explanation:
Here the value of the variable str1
is “Test String” so at the time of assigning value to str2
the double question mark operator (??) checks its left side variable (str1
) is null or not. As the variable str1
is not null it returns the left side string variable value “Test String“.