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 valuesControl 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:
a ?? b"Is
anull?" If yes, the answer isb; if no, it isa.
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.
What is 7 ~/ 2?
String? nick; What does nick ?? 'Fern' give?
With days = 2, what does days > 3 ? 'later' : 'today' give?
In a Dart 3 switch expression, what does the _ case do?
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 adouble; use~/for whole-number division.
