The conditional operators covered here are distinct from conditional statements such as if-else. They refer to the ternary operator and null-coalescing operator.
Two Types of Conditional Operators
Dart provides two concise conditional operators to replace verbose if-else blocks, letting you handle conditional assignment or return values in a single line.
- Ternary conditional operator:
condition ? expr1 : expr2 - Null-coalescing operator:
expr1 ?? expr2
Ternary operator syntax: condition ? expr1 : expr2
Syntax breakdown:
booleanCondition ? expressionIfTrue : expressionIfFalse
If condition evaluates to true, the operator returns expr1; if false, it returns expr2.
The condition must produce a boolean value, which determines one of the two results for assignment or return.
Example:
void main() {
bool isRain = true;
// Assign value via ternary expression
var result = isRain ? 'Raining' : 'Not raining';
print(result); // Raining
isRain = false;
result = isRain ? 'Raining' : 'Not raining';
print(result); // Not raining
}Code language: Dart (dart)
Program output:
D:\dartdemo\firstdart>dart run
Building package executable...
Built firstdart:firstdart.
Raining
Not rainingCode language: CSS (css)
If you’re already familiar with if-else, the equivalent logic can be written like this:
void main() {
bool isRain = true;
String result;
if (isRain) {
result = 'Raining';
} else {
result = 'Not raining';
}
print(result);//Raining
}Code language: Dart (dart)
Null-Coalescing Operator
Checks if a variable is null and quickly assigns a fallback default value.
Syntax: expr1 ?? expr2
nullableExpression ?? defaultValue
- If
expr1is not null, returnexpr1directly; - If
expr1equalsnull, returnexpr2
Official sample:
void main() {
// Accepts a nullable String parameter String?
String playerName(String? name) => name ?? 'Guest';
print(playerName("Tom")); // Tom
print(playerName(null)); // Guest
}Code language: JavaScript (javascript)
We define a function playerName that takes a nullable string. The ?? operator sets a fallback value: if the passed name is null, it defaults to “Guest”.
Additional Note
playerName here uses an arrow function, a shorthand syntax for functions which we will cover later. It is equivalent to the full function below:
String playerName(String? name) {
return name ?? 'Guest';
}Code language: Dart (dart)
Equivalent Implementation Comparisons
Implemented with ternary operator
String playerName(String? name) => name != null ? name : 'Guest';Code language: JavaScript (javascript)
Full if-else version
String playerName(String? name) {
if (name != null) {
return name;
} else {
return 'Guest';
}
}Code language: JavaScript (javascript)