On this page23 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is an if Statement?
- 2. The Shape of an if Statement
- 3. When the Condition Is false
- 4. A Block Can Hold Many Statements
- 5. A bool Variable as the Condition
- 6. Combining Conditions
- 7. Several Independent if Statements
- 8. Acting on a null Check
- 9. Top-Level Variables: Copy Them First
- 10. Acting on an is Check
- 11. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 22 — if Statements
| Category | 5 — Control Flow |
| Lecture | 022 of 140 |
| Estimated video length | 8 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
Until now every line of a program ran, every time. An
ifstatement lets a condition decide whether a piece of code runs at all.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways
Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.
Prerequisites
Students should already understand, from Lectures 004–021:
- variables,
int,double,bool,String, and string interpolation istype checks andint.tryParse(Lecture 010), andObject(Lecture 011)- nullable types and type promotion (Lectures 013 and 016)
- comparison operators
==,!=,<,>,<=,>=(Lecture 018) - logical operators
&&,||,!(Lecture 019)
Connection With Previous Lectures
In Lectures 018–021 we learned to ask questions and get bool answers:
bool hasPassed = marks >= 50;
print(hasPassed);But printing true or false is all we could do with the answer. We could not say "print
Congratulations only if the student passed" — every print ran no matter what. Several
lectures promised that if would fix this: acting on a comparison (Lecture 018), on an is
check (Lecture 010), and on a null check (Lecture 016). This lecture keeps those promises.
Learning Objectives
By the end of this lecture you will be able to:
- Understand what an
ifstatement does - Write an
ifstatement with a condition and a block - Predict what happens when the condition is
trueand when it isfalse - Use
boolvariables, comparisons, and&&,||,!as conditions - Use several independent
ifstatements in one program - Use
if (x != null)so Dart promotes a nullable variable - Use
if (x is Type)to safely use a value as a more specific type - Recognize the errors and silent bugs beginners meet with
if
1. What Is an if Statement?
An if statement runs a block of code only when a condition is true.
Analogy — think of a gate with a guard. The guard asks one yes-or-no question. If the answer is "yes", you walk through the gate; if it is "no", you skip that path and carry on.
void main() {
int marks = 72;
if (marks >= 50) {
print('Congratulations, you passed!');
}
print('Report finished.');
}Congratulations, you passed!
Report finished.2. The Shape of an if Statement
if (condition) {
// code that runs only when condition is true
}The keyword if, a condition in round brackets, then a block in curly braces { }.
The condition must be a bool — true or false. There is no semicolon after the ).
3. When the Condition Is false
If the condition is false, Dart skips the whole block and continues after the }.
void main() {
int marks = 38;
if (marks >= 50) {
print('Congratulations, you passed!');
}
print('Report finished.');
}Report finished.Same program, different value, different output. That is the whole point of if.
4. A Block Can Hold Many Statements
Everything between the braces belongs to the if: it all runs, or none of it does.
void main() {
double balance = 1200.0;
double price = 450.0;
if (balance >= price) {
balance -= price;
print('Purchase complete.');
print('New balance: $balance');
}
}Purchase complete.
New balance: 750.05. A bool Variable as the Condition
A well-named bool (Lecture 018) reads like a sentence. Use it directly — no == true.
void main() {
bool isRaining = true;
if (isRaining) {
print('Take an umbrella.');
}
}Take an umbrella.To act when something is not true, flip it with ! (Lecture 019): if (!isRaining).
6. Combining Conditions
Any bool expression works, including && and ||.
void main() {
int age = 20;
bool hasTicket = true;
if (age >= 18 && hasTicket) {
print('Welcome to the concert.');
}
}Welcome to the concert.7. Several Independent if Statements
Each if asks its own question. Dart checks every one, so zero, one, or several blocks can run.
void main() {
double temperature = 34.5;
if (temperature > 30) {
print('It is hot today.');
}
if (temperature < 10) {
print('It is cold today.');
}
if (temperature > 25) {
print('Drink plenty of water.');
}
}It is hot today.
Drink plenty of water.Choosing exactly one path out of several — "hot, otherwise cold, otherwise mild" — needs
else and else if, which come in Lecture 023.
8. Acting on a null Check
Lecture 016 showed that Dart promotes a nullable variable when it can see the value is
not null. An if with != null is the most common way to show it: inside the block, the
variable is treated as non-nullable.
void main() {
int? age = int.tryParse('19');
if (age != null) {
print('Next year you will be ${age + 1}.');
}
print('Done.');
}Next year you will be 20.
Done.age is an int?, yet age + 1 compiles inside the block. Try int.tryParse('abc'):
age is null, the block is skipped, and only Done. prints — no crash, no ! needed.
9. Top-Level Variables: Copy Them First
Lecture 016 warned that variables declared above main() are never promoted. An if
does not change that:
String? nickname = 'Zee';
void main() {
if (nickname != null) {
// print(nickname.length); // ✗
}
}Error: Property 'length' cannot be accessed on 'String?' because it is potentially null.
Try accessing using ?. instead.The fix: copy it into a local variable, then check the copy.
String? nickname = 'Zee';
void main() {
var name = nickname;
if (name != null) {
print('Nickname has ${name.length} letters.');
}
}Nickname has 3 letters.10. Acting on an is Check
In Lecture 011 we used as to treat an Object as a String — and it crashed when the value
was not one. With if and is (Lecture 010), Dart promotes the variable inside the block, so
no cast is needed and nothing can crash.
void main() {
Object item = 'Sara';
if (item is String) {
print('Text with ${item.length} letters');
}
if (item is int) {
print('A number: ${item + 1}');
}
}Text with 4 lettersInside the first block, item is a String, so .length works. The second block is
skipped because 'Sara' is not an int.
11. A Real-World Example
An ATM checks a withdrawal typed as text. Every tool from this lecture appears once.
void main() {
double balance = 5000.0;
bool isBlocked = false;
double? amount = double.tryParse('1500');
if (amount == null) {
print('Please enter a number.');
}
if (amount != null && !isBlocked && amount <= balance) {
balance -= amount;
print('Withdrew $amount');
}
print('Balance: $balance');
}Withdrew 1500.0
Balance: 3500.0amount != null comes first, so && short-circuits (Lecture 019) and amount is already
promoted when amount <= balance is checked. Change the text to 'abc' and you get
Please enter a number. and Balance: 5000.0.
Code Examples
Example 1 — A Simple Check
void main() {
int score = 95;
if (score > 90) {
print('Excellent!');
}
}Excellent!Example 2 — A Skipped Block
void main() {
int score = 60;
if (score > 90) {
print('Excellent!');
}
print('Score: $score');
}Score: 60Example 3 — A bool Variable
void main() {
bool isLoggedIn = true;
if (isLoggedIn) {
print('Welcome back, Ali.');
}
}Welcome back, Ali.Example 4 — Using !
void main() {
bool hasPaid = false;
if (!hasPaid) {
print('Payment is still due.');
}
}Payment is still due.Example 5 — A Range with &&
void main() {
int age = 15;
if (age >= 13 && age <= 19) {
print('Zayan is a teenager.');
}
}Zayan is a teenager.Example 6 — Checking Text
void main() {
String email = 'sara@example.com';
if (!email.contains('@')) {
print('Invalid email.');
}
if (email.contains('@')) {
print('Email looks fine.');
}
}Email looks fine.String methods such as contains (Lecture 008) return a bool, so they make good conditions.
Example 7 — Student Marks
void main() {
String name = 'Sara';
int marks = 88;
print('Student: $name');
if (marks >= 50) {
print('Result: passed');
}
if (marks >= 80) {
print('Award: merit certificate');
}
}Student: Sara
Result: passed
Award: merit certificateBoth conditions are true, so both blocks run — they are independent.
Example 8 — Shopping Total with Free Delivery
void main() {
int total = 2400;
int delivery = 200;
if (total >= 2000) {
delivery = 0;
print('Free delivery!');
}
print('Pay: ${total + delivery}');
}Free delivery!
Pay: 2400The if changes a variable, and the code after it uses the new value.
Example 9 — Reading a Temperature
void main() {
double? celsius = double.tryParse('41.5');
if (celsius != null && celsius > 40) {
print('Heat warning: $celsius °C');
}
}Heat warning: 41.5 °CExample 10 — Bonus Points in a Game
void main() {
int score = 120;
int lives = 3;
if (lives == 3) {
score += 50;
}
if (score > 150) {
print('New high score: $score');
}
}New high score: 170The first if changes score to 170, so the second condition is checked with the new value.
Common Beginner Mistakes
1. Using = instead of ==
void main() {
int score = 70;
// if (score = 50) { ... } // ✗
}Error: A value of type 'int' can't be assigned to a variable of type 'bool'.= assigns. To compare, write if (score == 50).
2. Using a number as a condition
void main() {
int items = 3;
// if (items) { ... } // ✗
}Error: A value of type 'int' can't be assigned to a variable of type 'bool'.Some languages treat 0 as false. Dart does not — write the question: if (items > 0).
3. A semicolon after the condition
void main() {
int marks = 40;
if (marks >= 50) ;
{
print('Passed');
}
}PassedThis compiles and prints Passed for a mark of 40! The ; ends the if with an empty
statement, and the block below runs every time. dart format pushes the ; away from
the ) to make it visible, and dart analyze flags it: Unnecessary empty statement.
4. Leaving out the braces
void main() {
int marks = 40;
if (marks >= 50) print('Passed');
print('Well done');
}Well doneWithout braces, only the first statement belongs to the if. dart analyze says:
Statements in an if should be enclosed in a block. Always use braces.
5. Using a variable from inside the block afterwards
void main() {
int marks = 80;
if (marks >= 50) {
String result = 'Passed';
}
// print(result); // ✗
}Error: Undefined name 'result'.A variable created inside { } exists only inside those braces. Declare it before the if
if you need it later.
6. Expecting a top-level variable to be promoted
if (nickname != null) does not promote a variable declared above main(). Copy it into a
local variable first (section 9).
Best Practices
- Always put the block in braces, even for one statement.
- Use
boolvariables directly:if (isOpen), notif (isOpen == true). - Give long conditions a name: store them in a
boolfirst, then writeif (canWithdraw). - Check for
nullwithif (x != null)instead of reaching for!. - Check a type with
if (x is T)instead of casting withas. - Put the
nullcheck first when joining conditions with&&.
Mini Challenge
Ali's phone battery is at 15 percent and power saving is off (isSaving = false). Print
Low battery! if the level is below 20, and Turn on power saving. if the level is below
20 and power saving is off. Always print Battery: 15% at the end.
Show solution
void main() {
int battery = 15;
bool isSaving = false;
if (battery < 20) {
print('Low battery!');
}
if (battery < 20 && !isSaving) {
print('Turn on power saving.');
}
print('Battery: $battery%');
}Low battery!
Turn on power saving.
Battery: 15%Practice Questions
Work through these in order — they run from beginner to application to challenge.
Beginner
- Store
age = 21. PrintAdultifageis at least18. - Store
isWeekend = false. PrintGo to school.if it is not the weekend. - Store
stock = 0. PrintOut of stockifstockequals0, then always printChecked.
Application
- Store
marks = 45. PrintPassedif marks are at least50, andNeeds supportif marks are below50, using two separateifstatements. - Store
price = 900andbalance = 1000. If the balance covers the price, subtract the price and printRemaining: …. - Store
temperature = 18.0. PrintPleasantif it is between15and25inclusive. - Use
int.tryParse('42')to get anint?. If it is notnull, print its double.
Challenge
- Declare
String? middleName = 'Raza';abovemain(). Insidemain(), printMiddle name: RAZA(upper case) only if a middle name exists. - Declare
Object value = 7;. If it is anint, printSquare: …; if it is aString, printLength: …. - Sara's cart total is
3500. Orders of3000or more get10percent off, and members (isMember = true) get200more off. Apply the discounts with twoifstatements and printPay: ….
Practice Answers
Question 1 — Solution
void main() {
int age = 21;
if (age >= 18) {
print('Adult');
}
}AdultQuestion 2 — Solution
void main() {
bool isWeekend = false;
if (!isWeekend) {
print('Go to school.');
}
}Go to school.Question 3 — Solution
void main() {
int stock = 0;
if (stock == 0) {
print('Out of stock');
}
print('Checked');
}Out of stock
CheckedQuestion 4 — Solution
void main() {
int marks = 45;
if (marks >= 50) {
print('Passed');
}
if (marks < 50) {
print('Needs support');
}
}Needs supportQuestion 5 — Solution
void main() {
int price = 900;
int balance = 1000;
if (balance >= price) {
balance -= price;
print('Remaining: $balance');
}
}Remaining: 100Question 6 — Solution
void main() {
double temperature = 18.0;
if (temperature >= 15 && temperature <= 25) {
print('Pleasant');
}
}PleasantQuestion 7 — Solution
void main() {
int? number = int.tryParse('42');
if (number != null) {
print(number * 2);
}
}84Question 8 — Solution
String? middleName = 'Raza';
void main() {
var middle = middleName;
if (middle != null) {
print('Middle name: ${middle.toUpperCase()}');
}
}Middle name: RAZAThe local copy middle can be promoted; the top-level middleName cannot.
Question 9 — Solution
void main() {
Object value = 7;
if (value is int) {
print('Square: ${value * value}');
}
if (value is String) {
print('Length: ${value.length}');
}
}Square: 49Question 10 — Solution
void main() {
double total = 3500;
bool isMember = true;
if (total >= 3000) {
total -= total * 0.10;
}
if (isMember) {
total -= 200;
}
print('Pay: $total');
}Pay: 2950.03500 minus 350 is 3150.0, and the member discount brings it to 2950.0.
Quick Revision
- What type must an
ifcondition have? - What happens when the condition is
false? - Why is
if (score = 50)an error? - What goes wrong with
if (marks >= 50);? - Why should you always use braces?
- What does
if (age != null)let you do inside the block? - Why doesn't
ifpromote a top-level variable, and what is the fix? - What does
if (item is String)give you thatas Stringdoes not?
Key Takeaways
- An
ifstatement runs its block only when its condition istrue; otherwise it skips it. - The condition must be a
bool— a comparison, aboolvariable, or a&&/||/!expression. Numbers are not conditions. - A block in braces can hold many statements; always use braces.
- Independent
ifstatements are each checked, so several can run. if (x != null)promotes a local nullable variable inside the block.- Top-level variables are never promoted — copy them into a local first.
if (x is T)promotesxtoTinside the block — a safe replacement foras.- A stray
;after the condition and missing braces are silent bugs;dart analyzecatches both.
What's Next?
Lecture 023 — if-else, else-if & Conditional Expressions. So far an if can only do
something or do nothing. Next we give it an alternative with else, chain several choices
with else if, and compare if with the conditional expression ? : from Lecture 020.