In this tutorial you will learn about the Dart Conditional Operators and its application with practical example.
Dart Conditional Operators ( ? : )
The conditional operator is considered as short hand for if-else statement. Conditional operator is also called as “Ternary Operator”.
Syntax 1:-
1 |
condition ? expOne : Exp |
If condition is true the expression will return expr1, if it is not it will return expr2.
Example:-
1 2 3 4 5 |
void main() { var res = 10 > 15 ? "Greater":"Smaller"; print(res); } |
Output:-
1 |
Smaller |
Syntax 2:-
1 |
expr1 ?? expr2 |
If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2.
Example:-
1 2 3 4 5 6 |
void main() { var n1 = null; var n2 = 15; var res = n1 ?? n2; print(res); } |
Output:-
1 |
15 |