Booleans & Conditions
Making Decisions in Code
Open interactive version (quiz + challenge)Real-world analogy
Booleans are like light switches -- they are either ON (true) or OFF (false). Conditions are like a choose-your-own-adventure book: 'If you have the key, open the door. Otherwise, find another way.' Your code makes decisions the same way -- checking true/false values to decide which path to take.
What is it?
Booleans are true/false values used for decision-making. Comparison operators (==, !=, >, =, <=) produce booleans. if/else and switch statements let your code choose different paths based on conditions. Logical operators (&&, ||, !) combine conditions. The ternary operator (? :) is a concise if/else for simple decisions.
Real-world relevance
Every app is full of decisions. Is the user logged in? Show the dashboard or the login screen. Is the cart empty? Show products or a message. Is the password valid? Allow login or show an error. Conditions are the logic that makes apps intelligent.
Key points
- Boolean Values — A bool in Dart can only be 'true' or 'false'. That is it -- two options. Booleans are the foundation of all decision-making in code. Every time your app decides what to show or what to do, a boolean is involved.
- Comparison Operators — Dart has 6 comparison operators: == (equal), != (not equal), > (greater), = (greater or equal), <= (less or equal). Each returns a bool -- true or false.
- if / else - Basic Decisions — 'if' checks a condition. If it is true, the code inside runs. 'else' runs when the condition is false. 'else if' adds more conditions in between. This is the most fundamental control flow in any programming language.
- Logical Operators: &&, ||, ! — && means AND (both must be true). || means OR (at least one true). ! means NOT (flips true to false). These let you combine multiple conditions into one decision.
- Ternary Operator ?: — The ternary operator is a shortcut for simple if/else. Syntax: condition ? valueIfTrue : valueIfFalse. It fits on one line and is great for assigning values based on a condition.
- switch Statement — switch checks a value against multiple cases. It is cleaner than many if/else chains when checking one variable against specific values. Each case needs a break (or return) to stop. 'default' handles unmatched cases.
- Dart 3 Switch Expressions — Dart 3 introduced switch expressions -- a modern, concise way to use switch that returns a value directly. No break needed! Use the => arrow syntax for each case.
- Null-Aware Conditions — Dart's null safety means a variable can be nullable (might be null). Use the ? operator to mark nullable types, ?? to provide a fallback, and ?. to safely access properties on nullable values.
- Assert - Debug-Time Checks — assert() checks a condition during development. If the condition is false, the app pauses with an error message. Asserts are removed in production builds, so they have zero cost. Great for catching bugs early.
Code example
void main() {
int age = 15;
bool hasPermission = true;
String role = 'student';
// if / else if / else
if (age >= 18) {
print('You are an adult');
} else if (age >= 13) {
print('You are a teenager');
} else {
print('You are a child');
}
// Logical operators
if (age >= 13 && hasPermission) {
print('Access granted!');
}
if (age < 5 || age > 65) {
print('Free entry!');
}
// Ternary operator
var status = age >= 18 ? 'Adult' : 'Minor';
print('Status: $status');
// switch expression (Dart 3)
var greeting = switch (role) {
'admin' => 'Welcome, Admin!',
'teacher' => 'Hello, Teacher!',
'student' => 'Hi, Student!',
_ => 'Hello, Guest!',
};
print(greeting);
// Null safety
String? nickname;
print('Nickname: ${nickname ?? "No nickname"}');
// Chained conditions
bool canDrive = age >= 16 && hasPermission && !false;
print('Can drive: $canDrive');
}Line-by-line walkthrough
- 1. The main function starts
- 2. Declaring age as 15
- 3. Declaring hasPermission as true
- 4. Declaring role as 'student'
- 5.
- 6. A comment for if/else if/else
- 7. Checking if age is 18 or more
- 8. If true, print 'You are an adult'
- 9. else if checks if age is 13 or more
- 10. If true, print 'You are a teenager' -- this runs for age 15
- 11. The else catches everything else
- 12. If neither condition above was true, print 'You are a child'
- 13.
- 14. A comment for logical operators
- 15. AND: both age >= 13 AND hasPermission must be true
- 16. Both are true, so 'Access granted!' prints
- 17.
- 18. OR: age 65 -- either one being true is enough
- 19. Age is 15, so neither is true -- this does not print
- 20.
- 21. A comment for ternary operator
- 22. If age >= 18, status is 'Adult', otherwise 'Minor'
- 23. Printing the status (will be 'Minor' since age is 15)
- 24.
- 25. A comment for switch expression
- 26. Using switch on the role variable
- 27. If role is 'admin', returns 'Welcome, Admin!'
- 28. If role is 'teacher', returns 'Hello, Teacher!'
- 29. If role is 'student', returns 'Hi, Student!' -- this matches!
- 30. The _ wildcard matches anything else (default)
- 31. Closing the switch expression with a semicolon
- 32. Printing the greeting
- 33.
- 34. A comment for null safety
- 35. Declaring nickname as nullable String, currently null
- 36. Using ?? to print 'No nickname' because nickname is null
- 37.
- 38. A comment for chained conditions
- 39. Combining three conditions with && to check if canDrive
- 40. Printing the result
Spot the bug
void main() {
int score = 85;
if score >= 90 {
print('A');
} else if (score >= 80)
print('B');
print('Good job!');
} else {
print('C');
}
}Need a hint?
Check the if condition syntax and the curly braces carefully...
Show answer
Two bugs: (1) if score >= 90 is missing parentheses -- must be if (score >= 90). (2) The else if block is missing an opening curly brace { after the condition. Fix: if (score >= 90) { and else if (score >= 80) {.
Explain like I'm 5
Imagine you are at a fork in the road. A signpost says: 'If you have a map, go left to the treasure. Otherwise, go right to ask for directions.' That is exactly how if/else works in code! The boolean (true/false) is like having or not having the map. Your code checks the condition and picks which way to go. The ternary operator is the shortcut: 'Map? Left : Right' -- same thing but shorter!
Fun fact
George Boole, born in 1815, invented Boolean algebra -- the math of true/false values. He never saw a computer! But his work became the foundation of ALL modern computing. Every digital device runs on billions of tiny true/false switches (transistors).
Hands-on challenge
Write a grading system. Given a score (0-100), use if/else to print the grade: 90+ is A, 80+ is B, 70+ is C, 60+ is D, below 60 is F. Then rewrite it using a switch expression. Which version do you prefer?
More resources
- Dart Branches (if/else, switch) (Dart Official)
- Dart Operators (Dart Official)
- Dart Patterns and Switch (Dart Official)