Thuta Learning
Dart
IntermediateProgrammingBeginner

If / Else

DartLesson 1125 min

What you'll walk away with

  • Write if / else if / else chains and order the conditions so the right branch wins
  • Explain why a Dart condition must be a bool and fix the compile error that if (count) produces
  • Combine conditions with &&, || and ! and use the ?: operator for small choices
  • Use Dart 3 features: if-case patterns, switch expressions and collection if

Explain it simply

Explain it simply

Think of an if statement as a fork in the road with a sign on it. The sign asks one yes-or-no question, such as "is it raining?", and the program takes the left path when the answer is yes and the right path when it is no. Dart walks up to the sign, answers the question, and from then on follows exactly one path.

An if / else if / else chain is several signs in a row. Dart reads them from the top, takes the first path whose question is answered yes, and ignores every sign after it. The final else is the path for everybody who said no to every question. The detail beginners must remember is that Dart only accepts real yes-or-no answers, a true or false value, and never a number or a piece of text that merely feels like a yes.

Problem → Why → Solution

The problem: a student with 95 gets a C

A teacher asks you for a grading function: 90 and above is an A, 80 and above is a B, 60 and above is a C. You write the three checks in the order they appear in that sentence, run it with a score of 95, and get a C. Nothing crashed and nothing was underlined in red, so the bug will only be found when a student complains.

The mistake is the order. Every score of 90 or more is also 60 or more, so the first check swallows every higher grade before the other checks get to look at it. Dart reports no error because the code is perfectly legal; it just does not mean what you intended.

grade_bug.dart
String grade(int score) {
  if (score >= 60) {
    return 'C';
  } else if (score >= 80) {
    return 'B';
  } else if (score >= 90) {
    return 'A';
  }
  return 'retry';
}

void main() {
  print(grade(95)); // prints C: the first condition already matched
}

Why does this happen?

Dart evaluates the conditions of an if / else if chain from top to bottom and runs only the first block whose condition is true. A score that matched an earlier branch never reaches the later conditions, so order is part of the logic. Put the narrowest, strictest test first (>= 90) and let the broader test (>= 60) and the final else catch whatever is left.

Core concept: chains, bool conditions and short-circuiting

An if statement evaluates a condition and runs its block only when the condition is true. Add else if for further questions and else as the catch-all. The chain stops at the first true condition: later branches are skipped even when their conditions would also be true, which is why the order of your checks is part of your logic. Dart does not require braces around a single statement, but write them anyway; a missing brace is a classic way to attach a second statement to the wrong branch.

text
How Dart walks the chain for score = 82
---------------------------------------
score >= 90 ?  --yes-->  'A'  (chain ends)
     | no
     v
score >= 80 ?  --yes-->  'B'  (chain ends)   <-- 82 stops here
     | no
     v
score >= 60 ?  --yes-->  'C'  (chain ends)
     | no
     v
else  ------------------>  'retry'

The condition must have type bool. Dart has no truthiness: an int, a String, a List and null are never silently treated as true or false. Code that works in JavaScript or Python, such as if (count) or if (name), is a compile error in Dart: "A value of type 'int' can't be assigned to a variable of type 'bool'." You write the question you actually mean instead: count > 0, name.isNotEmpty, items.isNotEmpty, value != null. It feels strict for a day and then saves you from the bugs where 0 or an empty string was perfectly valid data.

Combine conditions with && (and), || (or) and ! (not). Both && and || short-circuit: the right-hand side is evaluated only when the left side has not already decided the answer, so a check like user != null && user.isActive is safe for a local variable. && binds tighter than ||, and both bind tighter than the conditional operator, so isMember && price >= 30 ? 5 : 0 means (isMember && price >= 30) ? 5 : 0. When the precedence is not obvious to a reader, add parentheses or name the condition in a variable such as final isEligible = ...;.

Finally, remember that an if is a statement, not a value. When you only need to pick one of two values, the conditional expression condition ? a : b is shorter, and for several fixed cases a switch expression (shown below) reads better than a long else-if ladder.

Mental model: signs along a corridor
  1. Evaluate the first condition (a bool)
  2. true: run that block, skip all the rest
  3. false: move down to the next condition
  4. Nothing matched: run else, if present

Order is logic: the first true condition wins, so put the strictest test at the top.

General pattern

dart
if (condition) {
  // runs when condition is true
} else if (otherCondition) {
  // runs when only the second one is true
} else {
  // runs when nothing above matched
}

final result = condition ? valueIfTrue : valueIfFalse;

The condition goes in parentheses and must be a bool. else if and else are optional, and you can chain as many else if branches as you need. The conditional operator on the last line is the expression form: it produces a value instead of running statements.

Example: a grade function and a discount rule

This program has two small decision functions. grade() checks for an invalid score first, then walks down from the strictest grade to the loosest, and discount() combines two bool tests with && inside a conditional expression. The loop feeds grade() the boundary values 90, 89, 60 and 59, because that is where an off-by-one comparison hides. Predict the output before you run it.

decisions.dart
String grade(int score) {
  if (score < 0 || score > 100) {
    return 'invalid';
  } else if (score >= 90) {
    return 'A';
  } else if (score >= 80) {
    return 'B';
  } else if (score >= 60) {
    return 'C';
  } else {
    return 'retry';
  }
}

int discount(int price, bool isMember) {
  return isMember && price >= 30 ? 5 : 0;
}

void main() {
  for (final score in [95, 90, 89, 60, 59, 101]) {
    print('$score -> ${grade(score)}');
  }

  print('member, price 40: ${discount(40, true)} off');
  print('guest, price 40: ${discount(40, false)} off');
  print('member, price 20: ${discount(20, true)} off');
}

Code breakdown

  1. Validate firstif (score < 0 || score > 100) {

    || is true when either side is true, so impossible scores such as -3 or 101 are rejected before any grade is considered. Putting the rare invalid case first lets the later conditions assume the score is in range.

  2. Strictest grade first} else if (score >= 90) {

    Scores of 90 and above stop here and return 'A'. Because this test runs before >= 80, a 95 never reaches the lower checks. Swap the order and every score above 60 would become a C.

  3. Catch-all} else {

    Anything from 0 to 59 reaches else. No condition is written because else means "everything the earlier conditions did not match".

  4. Boundary valuesfor (final score in [95, 90, 89, 60, 59, 101]) {

    The test values sit right on the boundaries. 90 -> A and 89 -> B prove that >= includes the boundary, and 60 -> C versus 59 -> retry proves the next one.

  5. Two tests in onereturn isMember && price >= 30 ? 5 : 0;

    && is evaluated before ?:, so this is (isMember && price >= 30) ? 5 : 0. Only a member whose price is 30 or more gets 5; failing either test gives 0.

You should see
95 -> A
90 -> A
89 -> B
60 -> C
59 -> retry
101 -> invalid
member, price 40: 5 off
guest, price 40: 0 off
member, price 20: 0 off

Picking a value: ?: and switch expressions

Many ifs exist only to choose a value. The conditional operator handles two outcomes in one line: final label = price >= 30 ? 'big' : 'small';. With more than two outcomes, nested ?: chains become unreadable, and a Dart 3 switch expression reads like a table. Each case is pattern => value, cases are tried from top to bottom just like an else-if chain, and the whole expression must be exhaustive, so an int needs a final _ (wildcard). A case can carry a when guard for conditions a plain pattern cannot express.

temperature.dart
String describeTemp(int celsius) {
  return switch (celsius) {
    < 0 => 'freezing',
    < 15 => 'cold',
    < 28 => 'pleasant',
    final t when t > 40 => 'dangerous ($t C)',
    _ => 'hot',
  };
}

void main() {
  for (final t in [-5, 10, 20, 33, 45]) {
    print('$t -> ${describeTemp(t)}');
  }
  final price = 40;
  final label = price >= 30 ? 'big' : 'small';
  print(label);
}
ToolBest forWatch out for
if / else if / elseRunning different statements in each branchCondition order matters; always add braces
condition ? a : bChoosing between two values in one expressionDo not nest it more than once
switch expressionMany cases on one value that returns a valueMust be exhaustive, usually with a final _

Dart 3 patterns in if, and collection if

Dart 3 lets an if test the shape of a value and pull data out of it in one step. if (data case {'name': String name, 'age': int age}) checks that data is a map with those two keys holding those types; when it matches, name and age are ready to use inside the block, and otherwise the else branch runs. This replaces a pile of containsKey and is checks when you handle decoded JSON. A similar feature works inside list, set and map literals: an if element adds an item only when its condition is true, which is how you build a menu that depends on a role.

Plain type tests work too: after if (value is int && value > 40) the variable is promoted to int, so value + 1 needs no cast.

patterns.dart
void main() {
  final isAdmin = true;
  final menu = [
    'Home',
    'Profile',
    if (isAdmin) 'Admin panel',
  ];
  print(menu);

  Object? data = {'name': 'Su', 'age': 31};
  if (data case {'name': String name, 'age': int age}) {
    print('$name is $age');
  } else {
    print('unexpected shape');
  }

  data = {'name': 'Su', 'age': 'thirty'};
  if (data case {'name': String name, 'age': int age}) {
    print('$name is $age');
  } else {
    print('unexpected shape');
  }

  Object? input = 42;
  if (input is int && input > 40) {
    print(input + 1);
  }
}

In real projects

Where this shows up in real projects

Almost every feature you build starts with a decision. A login screen decides between showing the dashboard and the sign-in form, a checkout applies a discount only when a coupon is valid and the cart is above a minimum, and an API handler returns 404, 403 or 200 depending on what it finds. Validation code is mostly guard clauses: if the email is empty, return an error right away; if the password is too short, return another; only the valid path reaches the end of the function.

In Flutter, collection if is everywhere: a column of widgets can contain if (isAdmin) const AdminBanner() directly inside the list. Business rules such as shipping fees, tax bands and permission checks usually end up as chains or switch expressions, and teams test them with boundary values exactly like the loop in this lesson, because the bugs hide between 59 and 60, not at 75.

Common mistakes

Common mistakes

1. Putting the broadest condition first

As the problem showed, if (score >= 60) before if (score >= 90) captures every high score. Read the chain top to bottom and ask at each branch: could a value that belongs to a later branch be caught here? If so, move the stricter test up or add an upper bound with &&.

2. Using a non-bool as the condition

Writing if (items.length) or if (name) out of JavaScript habit fails to compile with "A value of type 'int' can't be assigned to a variable of type 'bool'." Ask the question explicitly: items.isNotEmpty, name.isNotEmpty or count > 0. Note that if (done = true) with a bool variable does compile: it assigns true, so the branch always runs. Compare with == or simply write if (done).

3. A switch expression without a catch-all

A switch expression over an int, a String or any other open set of values has to cover every possibility. Without a final _ => ... case, Dart refuses to compile it: "The type 'int' is not exhaustively matched by the switch cases since it doesn't match 'int()'." Add _ => ... for the leftovers, or a case such as final other => ... when you want to use the value.

Best practices

Best practices

  • Use early returns (guard clauses) for invalid input so the main path is not buried under nested else blocks.
  • Name a complicated condition, as in final canCheckout = cart.isNotEmpty && hasAddress;, because it reads better than a three-line if.
  • Prefer a switch expression over a long else-if ladder once you have four or more cases on one value.
  • Test the boundary values on both sides of every comparison.

Mini challenge

Mini challenge: museum ticket prices

Write two functions for a museum: one that turns an age into a group using an if / else if chain, and one that turns a group and a student flag into a ticket price using a switch expression.

  • ageGroup(age): 'invalid' below 0, 'infant' below 5, 'youth' below 18, 'adult' below 65, otherwise 'senior'
  • ticketPrice(group, isStudent): infant 0, youth 5, senior 4, adult 10 (7 for students), anything else -1
  • show(age, isStudent) prints one line such as "age 30 (adult, student): 7 units" and says "no ticket" when the price is -1
  • main() calls show() for ages -1, 3, 16, 30 (a student), 30 and 70
tickets.dart
String ageGroup(int age) {
  // TODO: 'invalid' below 0, 'infant' below 5, 'youth' below 18,
  //       'adult' below 65, otherwise 'senior'
  throw UnimplementedError();
}

int ticketPrice(String group, bool isStudent) {
  // TODO: switch expression: infant 0, youth 5, senior 4,
  //       adult 10 (7 for students), anything else -1
  throw UnimplementedError();
}

void show(int age, bool isStudent) {
  // TODO: print one line such as "age 30 (adult, student): 7 units"
}

void main() {
  // TODO: call show() for ages -1, 3, 16, 30 (student), 30 and 70
}

Expected: age -1 (invalid): no ticket age 3 (infant): 0 units age 16 (youth): 5 units age 30 (adult, student): 7 units age 30 (adult): 10 units age 70 (senior): 4 units

Show hint

In ageGroup start from the smallest limit and work upward: age < 0, then age < 5, then age < 18, so each branch can assume the earlier ones did not match. In ticketPrice write switch (group) { 'infant' => 0, ... _ => -1 } and use ?: inside the adult case.

Show solution
tickets.dart
String ageGroup(int age) {
  if (age < 0) {
    return 'invalid';
  } else if (age < 5) {
    return 'infant';
  } else if (age < 18) {
    return 'youth';
  } else if (age < 65) {
    return 'adult';
  } else {
    return 'senior';
  }
}

int ticketPrice(String group, bool isStudent) {
  return switch (group) {
    'infant' => 0,
    'youth' => 5,
    'senior' => 4,
    'adult' => isStudent ? 7 : 10,
    _ => -1,
  };
}

void show(int age, bool isStudent) {
  final group = ageGroup(age);
  final price = ticketPrice(group, isStudent);
  final who = isStudent ? '$group, student' : group;
  final text = price < 0 ? 'no ticket' : '$price units';
  print('age $age ($who): $text');
}

void main() {
  show(-1, false);
  show(3, false);
  show(16, false);
  show(30, true);
  show(30, false);
  show(70, false);
}

Quick quiz 1 / 3

A list called items exists. What happens when Dart compiles if (items.length) { print('has items'); }?

Quick quiz 2 / 3

What does this print? int s = 85; if (s >= 60) { print('C'); } else if (s >= 80) { print('B'); } else { print('F'); }

Quick quiz 3 / 3

The switch expression switch (score) { >= 90 => 'A', >= 80 => 'B' } over an int does not compile. What fixes it?

What to remember

  • An if / else if / else chain runs only the first block whose condition is true, so put the strictest test first.
  • Conditions must be bool: Dart has no truthiness, so write count > 0 or list.isNotEmpty instead of if (count).
  • && and || short-circuit, and ?: or a switch expression picks a value without a full if statement.
  • Dart 3 adds if-case patterns for checking shapes, switch expressions, and collection if for building lists.

Dart language overview — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

If / Else | Thuta Learning