Dart, lesson 4
Programs become interesting when they react differently to different input. The main tool
for that is if.
Dart checks each condition from the top. The first one that is true wins, its block runs,
and the rest are skipped. The else block runs only if nothing matched. The condition must
be a real bool: Dart will not treat 0 or an empty string as false.
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
2 exercises to try what you just read.
<>| less than / greater than |
<= >= | at most / at least |
== works for strings too: 'yes' == 'yes' is true. Comparisons are case-sensitive, so
'Yes' == 'yes' is false. Call .toLowerCase() on both sides when case shouldn't matter.
&& (and) is true only when both sides are true.|| (or) is true when at least one side is true.! (not) flips true and false.Dart stops evaluating as soon as it knows the answer. In a && b, if a is false, b is
never checked. This lets you write guards like list.isNotEmpty && list[0] == 'x' safely.
When you just need to pick one of two values, condition ? valueIfTrue : valueIfFalse is
shorter than a full if:
When one value decides between many outcomes, a switch expression is often clearest. Each
case is a pattern, followed by => and the result. _ matches anything left over:
Patterns can also compare. Relational patterns like >= 90 make grade tables tidy:
Cases are tried from top to bottom, so put the most specific ones first. Dart also checks the
switch is exhaustive: if some value could fall through every case, it is a compile error.
That is why the _ case is there.
A switch statement exists too, for running blocks of code rather than producing a value.
In Dart 3 its cases don't fall through, so you don't need break.
A cinema prices tickets by age. Read an age (a whole number) and print the price:
FreeChild: 6Adult: 11Senior: 7Input:
Output:
A year is a leap year if it is divisible by 4, except years divisible by 100, which are
leap years only if they are also divisible by 400. Read a year and print leap or
common.
Input:
Output:
final temperature = 31;
if (temperature > 30) {
print('Hot day. Drink water.');
} else if (temperature < 5) {
print('Cold day. Grab a coat.');
} else {
print('Nice weather.');
}final age = 15;
final withParent = true;
if (age >= 18 || withParent) {
print('You can watch the film.');
}final label = score >= 50 ? 'pass' : 'fail';final day = 'sat';
final plan = switch (day) {
'sat' || 'sun' => 'Weekend!',
'fri' => 'Almost there',
_ => 'Work day',
};final grade = switch (score) {
>= 90 => 'A',
>= 80 => 'B',
_ => 'C or below',
};9Child: 62024leap