Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Basics of Dart  ›  Capstone Project

Operators and Control Flow

Control Flow Statements 15 minOperators such as integer division and the null-aware operators compute values, while if, loops and switch decide which statements run.

Operators and Control Flow

Every morning Sprout must answer one question: which plants need water today? That takes both halves of this lesson. Operators compute values like "days since watering", and control flow decides which lines run for each plant.

The rule

Operators make a value; control flow chooses what runs next.

Operators worth knowing early

7 / 2     // 3.5  — division always gives a double
7 ~/ 2    // 3    — integer division drops the remainder
7 % 2     // 1    — the remainder
days >= every            // comparison, gives a bool
name ?? 'Unnamed'        // if name is null, use 'Unnamed'
plant?.name              // if plant is null, the result is null instead of a crash
days ??= 7;              // assign 7 only if days is null
days > 3 ? 'later' : 'soon'   // choose between two values

Control flow

for (final p in plants) {
  if (p.daysSince >= p.every) {
    print('${p.name} is due');
  } else if (p.daysSince == p.every - 1) {
    print('${p.name} is due tomorrow');
  }
}

final label = switch (plant.every) {
  1 => 'daily',
  7 => 'weekly',
  _ => 'every ${plant.every} days',
};

for-in walks a collection, while repeats until a condition is false, and a switch picks one branch. In Dart 3 a switch expression produces a value, _ matches anything left, and a case with a body never falls through into the next one.

The shortcut

Read null-aware operators as questions about the left side:

Decoding the question-mark operatorsStep 1 of 4
  1. a ?? b

    "Is a null?" If yes, the answer is b; if no, it is a.

The trap is / versus ~/. Splitting 7 litres over 2 days with / gives 3.5, a double, and assigning that to an int is a compile error. Use ~/ when you want whole numbers.

Drills

Answer fast — trust the rule.

quick drill

What is 7 ~/ 2?

quick drill

String? nick; What does nick ?? 'Fern' give?

quick drill

With days = 2, what does days > 3 ? 'later' : 'today' give?

quick drill

In a Dart 3 switch expression, what does the _ case do?

quick drill

int? since; since ??= 4; since ??= 9; What is since now?

Remember

  • Operators make a value; control flow chooses what runs next.
  • ??, ?. and ??= all first ask: is the left side null?
  • Trap: / always gives a double; use ~/ for whole-number division.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWho needs water today?

Sprout has a List of plants, each with a name and an int? daysSince (null if never watered) and an int every. Write the loop that prints each plant that is due, treating never-watered plants as due, and explain which operator handles the null and why.