If, Else, and Conditionals
Branching logic with if/else, ternary expressions, and Dart's pattern-aware if-case syntax.
2 menit membaca
Conditional logic in Dart starts exactly where you'd expect if you know any C-family language, then adds a couple of conveniences worth knowing about early.
if / else if / else
int score = 82;
if (score >= 90) {
print('Grade: A');
} else if (score >= 80) {
print('Grade: B');
} else if (score >= 70) {
print('Grade: C');
} else {
print('Grade: F');
}Dart requires the condition to evaluate to an actual bool — unlike JavaScript, if (someString) or if (0) won't compile. This closes off a whole class of "truthy/falsy" bugs where a value like an empty string or a zero accidentally behaves like false.
String input = '';
// if (input) { ... } // compile error: not a bool
if (input.isNotEmpty) { ... } // explicit, and correctThe ternary operator
For a simple two-way choice that produces a value, the ternary operator (condition ? ifTrue : ifFalse) is more concise than a full if/else:
int age = 20;
String category = age >= 18 ? 'adult' : 'minor';
print(category); // adultReach for it when both branches are short expressions. Once either branch needs more than one statement, an if/else reads more clearly than a nested ternary.
Null-aware conditionals
Combining what you saw with ?? in the previous lesson, conditionals often exist just to supply a default for a possibly-missing value — which ?? frequently replaces outright:
String? city;
// Equivalent, but the second is shorter and just as clear:
String result1 = city != null ? city : 'Unknown';
String result2 = city ?? 'Unknown';Pattern matching with if-case
Modern Dart adds an if-case form that tests a value against a pattern and, if it matches, binds part of it to a new variable in the same step:
Object input = [1, 2, 3];
if (input case [int first, int second, ...]) {
print('Starts with $first, $second');
} else {
print('Did not match');
}Here, the pattern [int first, int second, ...] checks that input is a list with at least two int elements, and if so, destructures the first two into first and second right in the condition. You won't need this often as a beginner, but recognizing it will save confusion the first time you see it in someone else's code — it's an if, just one that can also unpack its subject.
Conditionals are the backbone of almost every non-trivial program, and everything after this lesson — loops, switch statements, and eventually functions that decide what to return — builds directly on the same true/false logic you just saw.