DMarlon Studio

Lesson 6 · 6 of 20

if, else and the conditional operator · Dart

Make decisions in Dart with if, else if and else, combine conditions with &&, || and !, and pick a value in one line with the ? : operator.

Dart · if, else and the conditional operator in DMarlon Studio: the example's code and its output in the terminal

`if` runs its block only when the condition in brackets is true. Since temperature is 31, temperature > 30 is true and the program tells you to drink water. The comparison operators are >, <, >=, <=, == (equal) and != (not equal).

`else if` and `else` choose one path out of several: Dart tries the conditions in order and takes the first one that holds. With 72 points, score >= 90 is false and score >= 70 is true, so grade becomes 'B' and the rest is never checked.

Look at String grade;: the variable is declared without a value and each branch gives it one. Dart checks that, whatever happens, grade will have a value before it is used; without the final else, it would not compile.

Conditions combine with `&&` (and), `||` (or) and `!` (not). age >= 18 || withParent holds because, although they are 16, they come with an adult. When the block is a single statement, it can sit on the same line without braces.

The conditional operator condition ? valueIfTrue : valueIfFalse picks a value in a single expression: age < 18 ? 'junior' : 'adult'. It even fits inside ${} to print pass or fail without a separate if.

Code · main.dart

void main() {  int temperature = 31;  // if runs its block only when the condition is true.  if (temperature > 30) {    print('It is $temperature degrees: drink water.');  }  // else if and else choose one path out of several.  int score = 72;  String grade;  if (score >= 90) {    grade = 'A';  } else if (score >= 70) {    grade = 'B';  } else if (score >= 50) {    grade = 'C';  } else {    grade = 'F';  }  print('Score $score: grade $grade');  // && (and), || (or) and ! (not) combine conditions.  int age = 16;  bool withParent = true;  bool isWeekend = false;  if (age >= 18 || withParent) print('You can see the film.');  if (!isWeekend && temperature > 25) print('A hot working day.');  print('Is it a B? ${grade == 'B'}');  // condition ? valueIfTrue : valueIfFalse  String ticket = age < 18 ? 'junior' : 'adult';  print('Ticket: $ticket, result: ${score >= 50 ? 'pass' : 'fail'}');}

Output · dart run main.dart

It is 31 degrees: drink water.
Score 72: grade B
You can see the film.
A hot working day.
Is it a B? true
Ticket: junior, result: pass

Key points

  • if (condition) { } only runs when it is true.
  • else if and else take the first path that holds.
  • == compares; = assigns.
  • &&, || and ! combine conditions.
  • c ? a : b picks one of two values.

Exercise

Write a program that, depending on an hour variable from 0 to 23, says Good morning, Good afternoon or Good evening, and adds (weekend) with the conditional operator when isWeekend is true.