Dart Ternary Operator

Dart Ternary Operator is used to write a conditional expression, where based on the result of a boolean condition, one of the two values is selected.

Syntax

The syntax of using Ternary Operator (?:) for a conditional expression is

</>
Copy
condition ? value1 : value2

If condition evaluates to true, then value1 is returned, or if the condition is false, value2 is returned.

Examples

In the following example, we write a conditional expression that returns a value: 'Apple' or 'Banana' based on the result of a boolean condition.

main.dart

</>
Copy
void main() {
  var selection = 1;
  var output = (selection == 1) ? 'Apple' : 'Banana';
  print(output);
}

Output

Apple

Since, given condition evaluates to true, ‘Apple’ is returned by the Ternary Operator.

Now, let us assign a different value to the selection variable, and observe the output.

main.dart

</>
Copy
void main() {
  var selection = 2;
  var output = (selection == 1) ? 'Apple' : 'Banana';
  print(output);
}

Output

Banana

Conclusion

In this Dart Tutorial, we learned about Ternary Operator, and how to this Ternary Operator to create a conditional expression, with examples.