← Dart tutorial

Dart

Conditionals

if, else if, and else work the same as in Java, JavaScript, or C#.

Example: a time-of-day greeting

void main() {
  int hour = 14;
  String greeting;

  if (hour < 12) {
    greeting = 'Good morning';
  } else if (hour < 18) {
    greeting = 'Good afternoon';
  } else {
    greeting = 'Good evening';
  }

  print(greeting);
}
Good afternoon

By now this exact structure should be recognizable from several other subjects in this tutorial — that's a genuinely useful thing to notice: across nearly every mainstream language, if/else if/else branching is close to identical, so it's one of the fastest concepts to transfer once you've truly learned it in any single language.

Example
void main() {
  int hour = 14;
  String greeting;

  if (hour < 12) {
    greeting = 'Good morning';
  } else if (hour < 18) {
    greeting = 'Good afternoon';
  } else {
    greeting = 'Good evening';
  }

  print(greeting);
}
Output
Good afternoon