If Else in Dart

Branching with if and else in Dart is straightforward.

void main() {
  // Here's a basic example.
  if (7 % 2 == 0) {
    print('7 is even');
  } else {
    print('7 is odd');
  }

  // You can have an `if` statement without an else.
  if (8 % 4 == 0) {
    print('8 is divisible by 4');
  }

  // Logical operators like `&&` and `||` are often
  // useful in conditions.
  if (8 % 2 == 0 || 7 % 2 == 0) {
    print('either 8 or 7 are even');
  }

  // A statement can precede conditionals; any variables
  // declared in this statement are available in the current
  // and all subsequent branches.
  var num = 9;
  if (num < 0) {
    print('$num is negative');
  } else if (num < 10) {
    print('$num has 1 digit');
  } else {
    print('$num has multiple digits');
  }
}

To run the program:

$ dart if_else.dart
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that you don’t need parentheses around conditions in Dart, but the braces are required.

Dart, like many other languages, doesn’t have a ternary if operator. However, it does have a conditional expression that can be used for simple conditionals:

var result = condition ? valueIfTrue : valueIfFalse;

This can be useful for assigning values based on a condition, but for more complex logic, a full if statement is necessary.