Conditional expressions
Dart has two operators that let you concisely evaluate expressionsthat might otherwise require if-else statements:
condition ? expr1 : expr2
- If condition is true, evaluates expr1 (and returns its value);otherwise, evaluates and returns the value of expr2.
expr1 ?? expr2
- If expr1 is non-null, returns its value;otherwise, evaluates and returns the value of expr2.
When you need to assign a valuebased on a boolean expression,consider using ?:
.
var visibility = isPublic ? 'public' : 'private';
If the boolean expression tests for null,consider using ??
.
String playerName(String name) => name ?? 'Guest';
The previous example could have been written at least two other ways,but not as succinctly:
// Slightly longer version uses ?: operator.
String playerName(String name) => name != null ? name : 'Guest';
// Very long version uses if-else statement.
String playerName(String name) {
if (name != null) {
return name;
} else {
return 'Guest';
}
}