This tutorial shows you how to write a Conditional operator in Dart Programming.
There are two types of conditional Operators in Dart.
- Ternary Operator
- Null-coalescing operators
Ternary Operator in Dart example
Ternary operators in the Dart language.
conditional_expression ? statement1 : statement2;
Conditional_expression
is a valid dart expression, that evaluates to true or false.
statement1
: Dart statements to execute if the condition is evaluated to be true.statement2
: Dart statements to execute if the condition is evaluated to false.
It is equivalent to following if else syntax.
if (conditional_expression) {
statement1;
} else {
statement2;
}
if true
, statement1
is executed, else statement2
is executed.
Here is an example
void main(){
var age = 45;
age > 60 ? print("Senior Citizen") : print("Not Senior Citizen");
}
Dart Null-coalescing operators examples
Nullish Coalescing Operator is a new feature in Dart
and its symbol is ??
i.e. double question mark
.
Logical and shortcircuit operator that operates on two operands and returns its value of
- right-hand operand value when the left-hand operand is
null
orundefined
- left-hand operand value when the left-hand operand is not
null
orundefined
This will be useful for defaulting to a fallback value when object properties are null or undefined.
Syntax:
Left Operand ?? Right Operand
Here is an example
void main(){
var str=null;
print(str ?? 'default'); //default
var str1="one";
print(str1 ?? 'default'); // one
}