📜  dart inline if else - Dart (1)

📅  最后修改于: 2023-12-03 15:30:21.887000             🧑  作者: Mango

Dart Inline If-Else

Dart provides an inline if-else statement that allows developers to write a conditional expression in a concise and readable way. This statement is also known as ternary operators.

Syntax

The syntax of the inline if-else statement is as follows:

(condition) ? true_expression : false_expression;

The condition is evaluated first. If the condition is true, then the true_expression is evaluated and returned. Otherwise, the false_expression is evaluated and returned.

Example

Let's see an example of the inline if-else statement:

int x = 10;
int y = 20;
String result = (x > y) ? 'x is greater than y' : 'y is greater than x';
print(result); // Output: y is greater than x

In the above example, the condition (x > y) is evaluated first. Since this condition is not true, the false_expression 'y is greater than x' is evaluated and assigned to the result variable.

Nesting

The inline if-else statement can also be nested to express complex conditions. Let's see an example:

int x = 10;
int y = 20;
String result = (x > y)
  ? 'x is greater than y'
  : (x < y)
    ? 'x is less than y'
    : 'x and y are equal';
print(result); // Output: x is less than y

In the above example, we have nested the inline if-else statement to check if x is greater than y, less than y, or equal to y. The condition (x < y) is true, so the second true_expression 'x is less than y' is evaluated and assigned to the result variable.

Overall, the inline if-else statement is a powerful feature of Dart that allows developers to write concise and readable conditional expressions.