Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 61 ยท Control Flow

if, else and Conditional Expressions

Learn Dart conditionals: if and else if chains, the ternary operator, ?? for defaults, collection if and else inside list, set and map literals, and guard clauses.

Programs become useful when they can choose. Show a welcome banner only to new users, pick a discount by order size, or leave out a menu item the current user may not use. Dart gives you four tools for this: the if statement, the conditional (ternary) expression, the if-null operator ??, and a feature unique to Dart's collection literals, the collection if.

This lesson covers all four, plus a few habits that keep conditional code readable. The next lessons build on it with loops, switch and pattern matching. Real Dart appears in read-only blocks, with TypeScript stand-ins where the idea can be run.

The if statement

The shape is the same as in C, Java and JavaScript. The condition goes in parentheses and must be a bool; there is no truthiness (see Booleans and Operators).

DART
void main() {
  var temperature = 31;

  if (temperature > 30) {
    print('Hot day');
  } else if (temperature > 18) {
    print('Pleasant');
  } else {
    print('Bring a jacket');
  }
}
TEXT
Hot day

Dart evaluates the branches from the top and runs the first one whose condition is true. The final else is optional. You can drop the braces for a single statement, but the Dart style guide asks you to keep them except for the shortest one-liners that fit on one line. Braces prevent the classic bug where a second line looks like part of the if but is not.

flowchart TD
    S["temperature = 31"] --> C1{"temperature > 30?"}
    C1 -- "yes" --> A["print Hot day"]
    C1 -- "no" --> C2{"temperature > 18?"}
    C2 -- "yes" --> B["print Pleasant"]
    C2 -- "no" --> D["print Bring a jacket"]

An if / else if / else chain runs exactly one branch: the first whose condition is true.

An if is a statement, not an expression. You cannot write var label = if (x) 'a' else 'b';. For a value, use the conditional expression below.

TypeScript An if / else if chain (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Guard clauses

Deeply nested if statements are hard to read. A common cure is the guard clause: handle the unusual case first and return early, so the main path stays flat.

DART
String shippingLabel(String? country, double weightKg) {
  if (country == null) return 'Unknown destination';
  if (weightKg <= 0) return 'Invalid weight';

  // From here on country is a String, promoted by the null check.
  var zone = country == 'US' ? 'domestic' : 'international';
  return '$zone, ${weightKg.toStringAsFixed(1)} kg';
}

Notice the benefit for null safety: after if (country == null) return ..., the variable is promoted to a non-nullable String for the rest of the function (see Null Safety).

The conditional expression

For a simple choice between two values, the ternary operator is shorter than an if:

DART
void main() {
  var items = 3;
  var label = items == 1 ? 'item' : 'items';
  print('$items $label');                // 3 items

  var age = 20;
  print(age >= 18 ? 'adult' : 'minor');  // adult
}

The syntax is condition ? valueIfTrue : valueIfFalse. It is an expression, so it can sit inside string interpolation, arguments or return statements. Keep each use simple. Nesting ternaries, such as a ? b : c ? d : e, quickly becomes puzzling; switch to an if chain or a switch expression (covered in a later lesson).

Defaults with ??

Choosing a fallback when a value may be missing is so common that Dart has a dedicated operator. a ?? b means "a, unless it is null, then b":

DART
void main() {
  String? userName;
  print('Hello, ${userName ?? 'guest'}');   // Hello, guest

  userName = 'Ada';
  print('Hello, ${userName ?? 'guest'}');   // Hello, Ada
}

Use ?? for null checks and ?: for boolean checks. Mixing them up is a frequent beginner mistake: name ?? 'guest' does not fall back when name is an empty string, only when it is null. If you want both, write (name == null || name.isEmpty) ? 'guest' : name.

TypeScript Ternary and nullish defaults (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Collection if and collection else

Here is a feature JavaScript lacks. Inside a list, set or map literal, you can put an if (and an optional else) directly between the elements. The element is included only when the condition holds.

DART
void main() {
  var isAdmin = true;
  var hasMessages = false;

  var menu = [
    'Home',
    'Profile',
    if (isAdmin) 'Admin panel',
    if (hasMessages) 'Inbox' else 'Inbox (empty)',
  ];
  print(menu);
}
TEXT
[Home, Profile, Admin panel, Inbox (empty)]

Without this feature you would build the list, then call add inside separate if statements. The collection if keeps the whole shape of the data in one place, which matters a lot in Flutter code where long lists of widgets are common. It also works in sets and maps:

DART
void main() {
  var debug = true;

  var config = {
    'name': 'demo',
    if (debug) 'logLevel': 'verbose',
  };
  print(config);            // {name: demo, logLevel: verbose}

  var tags = <String>{'dart', if (debug) 'debug'};
  print(tags);              // {dart, debug}
}

You can spread several elements at once by combining if with ...:

DART
var extra = true;
var items = ['a', 'b', if (extra) ...['c', 'd']];   // [a, b, c, d]

The sibling feature, for inside a collection, is described in the lesson on loops. Both are evaluated each time the literal is evaluated, so they always reflect the current values.

TypeScript Building a list with conditions (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

if with case

Dart 3 adds a way to test and unpack a value in one step: if (value case pattern). It is covered fully in the lesson on patterns, but a taste shows why it matters:

DART
void main() {
  Object? input = 'Ada Lovelace';

  if (input case String text when text.length > 5) {
    print('A long name: $text');
  } else {
    print('Something else');
  }
}

Here the case clause checks that input is a String, binds it to text, and the when guard adds an extra test. If you only need to compare one value against many constants, a switch is usually clearer than a long chain of else if; see switch Statements and Expressions.

Readable conditions

A few habits make conditionals pleasant to read:

  • Name complex conditions. final canCheckout = cart.isNotEmpty && user.isVerified && !cart.hasOutOfStock; then if (canCheckout).
  • Prefer positive conditions and avoid double negatives like !isNotReady.
  • Do not compare booleans to literals. Write if (isReady), not if (isReady == true).
  • Return a boolean directly. bool isAdult(int age) => age >= 18; instead of an if that returns true or false.
  • Order checks from most specific to most general in an else if chain, since the first match wins.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which if condition is valid Dart?

    Conditions must be bool. Only the comparison count > 0 produces a bool; the other forms rely on truthiness that Dart does not have.
  2. 2. What is printed by print(items == 1 ? 'item' : 'items'); when items is 2?

    The condition items == 1 is false, so the expression evaluates to the value after the colon, 'items'.
  3. 3. When does name ?? 'guest' return 'guest'?

    The if-null operator only looks at null. An empty string is a valid, non-null value and is returned as is.
  4. 4. What does ['a', if (flag) 'b', 'c'] produce when flag is false?

    A collection if adds its element only when the condition is true. When it is false, nothing is inserted, not even null.
  5. 5. Why can't you write var x = if (ok) 1 else 2; in Dart?

    The if statement does not produce a value. Use ok ? 1 : 2 or a switch expression instead.

Summary

  • if conditions must be booleans; chain branches with else if and finish with an optional else.
  • Use guard clauses (early return) to keep the main path flat; null checks promote variables afterwards.
  • condition ? a : b is an expression for a choice between two values; keep it simple.
  • a ?? b supplies a default only when a is null.
  • A collection if (with an optional else, and ... spreads) builds lists, sets and maps conditionally.
  • if (value case pattern) tests and unpacks a value in one step; patterns are covered later.

Next, repeat actions with Loops: for, while and do-while.