Watch the video (8 min)
On this page23 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is an if Statement?
  5. 2. The Shape of an if Statement
  6. 3. When the Condition Is false
  7. 4. A Block Can Hold Many Statements
  8. 5. A bool Variable as the Condition
  9. 6. Combining Conditions
  10. 7. Several Independent if Statements
  11. 8. Acting on a null Check
  12. 9. Top-Level Variables: Copy Them First
  13. 10. Acting on an is Check
  14. 11. A Real-World Example
  15. Code Examples
  16. Common Beginner Mistakes
  17. Best Practices
  18. Mini Challenge
  19. Practice Questions
  20. Practice Answers
  21. Quick Revision
  22. Key Takeaways
  23. What's Next?

Lecture 22 — if Statements

Category5 — Control Flow
Lecture022 of 140
Estimated video length8 min
TargetDart 3.12.2
LevelBeginner

Until now every line of a program ran, every time. An if statement 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
  • is type checks and int.tryParse (Lecture 010), and Object (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:

dart
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 if statement does
  • Write an if statement with a condition and a block
  • Predict what happens when the condition is true and when it is false
  • Use bool variables, comparisons, and &&, ||, ! as conditions
  • Use several independent if statements 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.

dart
void main() {
  int marks = 72;
  if (marks >= 50) {
    print('Congratulations, you passed!');
  }
  print('Report finished.');
}
output
Congratulations, you passed!
Report finished.

2. The Shape of an if Statement

dart
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 }.

dart
void main() {
  int marks = 38;
  if (marks >= 50) {
    print('Congratulations, you passed!');
  }
  print('Report finished.');
}
output
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.

dart
void main() {
  double balance = 1200.0;
  double price = 450.0;
  if (balance >= price) {
    balance -= price;
    print('Purchase complete.');
    print('New balance: $balance');
  }
}
output
Purchase complete.
New balance: 750.0

5. A bool Variable as the Condition

A well-named bool (Lecture 018) reads like a sentence. Use it directly — no == true.

dart
void main() {
  bool isRaining = true;
  if (isRaining) {
    print('Take an umbrella.');
  }
}
output
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 ||.

dart
void main() {
  int age = 20;
  bool hasTicket = true;
  if (age >= 18 && hasTicket) {
    print('Welcome to the concert.');
  }
}
output
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.

dart
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.');
  }
}
output
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.

dart
void main() {
  int? age = int.tryParse('19');
  if (age != null) {
    print('Next year you will be ${age + 1}.');
  }
  print('Done.');
}
output
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:

dart
String? nickname = 'Zee';

void main() {
  if (nickname != null) {
    // print(nickname.length); // ✗
  }
}
output
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.

dart
String? nickname = 'Zee';

void main() {
  var name = nickname;
  if (name != null) {
    print('Nickname has ${name.length} letters.');
  }
}
output
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.

dart
void main() {
  Object item = 'Sara';
  if (item is String) {
    print('Text with ${item.length} letters');
  }
  if (item is int) {
    print('A number: ${item + 1}');
  }
}
output
Text with 4 letters

Inside 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.

dart
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');
}
output
Withdrew 1500.0
Balance: 3500.0

amount != 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

dart
void main() {
  int score = 95;
  if (score > 90) {
    print('Excellent!');
  }
}
output
Excellent!

Example 2 — A Skipped Block

dart
void main() {
  int score = 60;
  if (score > 90) {
    print('Excellent!');
  }
  print('Score: $score');
}
output
Score: 60

Example 3 — A bool Variable

dart
void main() {
  bool isLoggedIn = true;
  if (isLoggedIn) {
    print('Welcome back, Ali.');
  }
}
output
Welcome back, Ali.

Example 4 — Using !

dart
void main() {
  bool hasPaid = false;
  if (!hasPaid) {
    print('Payment is still due.');
  }
}
output
Payment is still due.

Example 5 — A Range with &&

dart
void main() {
  int age = 15;
  if (age >= 13 && age <= 19) {
    print('Zayan is a teenager.');
  }
}
output
Zayan is a teenager.

Example 6 — Checking Text

dart
void main() {
  String email = 'sara@example.com';
  if (!email.contains('@')) {
    print('Invalid email.');
  }
  if (email.contains('@')) {
    print('Email looks fine.');
  }
}
output
Email looks fine.

String methods such as contains (Lecture 008) return a bool, so they make good conditions.

Example 7 — Student Marks

dart
void main() {
  String name = 'Sara';
  int marks = 88;
  print('Student: $name');
  if (marks >= 50) {
    print('Result: passed');
  }
  if (marks >= 80) {
    print('Award: merit certificate');
  }
}
output
Student: Sara
Result: passed
Award: merit certificate

Both conditions are true, so both blocks run — they are independent.

Example 8 — Shopping Total with Free Delivery

dart
void main() {
  int total = 2400;
  int delivery = 200;
  if (total >= 2000) {
    delivery = 0;
    print('Free delivery!');
  }
  print('Pay: ${total + delivery}');
}
output
Free delivery!
Pay: 2400

The if changes a variable, and the code after it uses the new value.

Example 9 — Reading a Temperature

dart
void main() {
  double? celsius = double.tryParse('41.5');
  if (celsius != null && celsius > 40) {
    print('Heat warning: $celsius °C');
  }
}
output
Heat warning: 41.5 °C

Example 10 — Bonus Points in a Game

dart
void main() {
  int score = 120;
  int lives = 3;
  if (lives == 3) {
    score += 50;
  }
  if (score > 150) {
    print('New high score: $score');
  }
}
output
New high score: 170

The first if changes score to 170, so the second condition is checked with the new value.


Common Beginner Mistakes

1. Using = instead of ==

dart
void main() {
  int score = 70;
  // if (score = 50) { ... } // ✗
}
output
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

dart
void main() {
  int items = 3;
  // if (items) { ... } // ✗
}
output
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

dart
void main() {
  int marks = 40;
  if (marks >= 50) ;
  {
    print('Passed');
  }
}
output
Passed

This 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

dart
void main() {
  int marks = 40;
  if (marks >= 50) print('Passed');
  print('Well done');
}
output
Well done

Without 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

dart
void main() {
  int marks = 80;
  if (marks >= 50) {
    String result = 'Passed';
  }
  // print(result); // ✗
}
output
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 bool variables directly: if (isOpen), not if (isOpen == true).
  • Give long conditions a name: store them in a bool first, then write if (canWithdraw).
  • Check for null with if (x != null) instead of reaching for !.
  • Check a type with if (x is T) instead of casting with as.
  • Put the null check 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
dart
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%');
}
output
Low battery!
Turn on power saving.
Battery: 15%

Practice Questions

Work through these in order — they run from beginner to application to challenge.

Beginner

  1. Store age = 21. Print Adult if age is at least 18.
  2. Store isWeekend = false. Print Go to school. if it is not the weekend.
  3. Store stock = 0. Print Out of stock if stock equals 0, then always print Checked.

Application

  1. Store marks = 45. Print Passed if marks are at least 50, and Needs support if marks are below 50, using two separate if statements.
  2. Store price = 900 and balance = 1000. If the balance covers the price, subtract the price and print Remaining: ….
  3. Store temperature = 18.0. Print Pleasant if it is between 15 and 25 inclusive.
  4. Use int.tryParse('42') to get an int?. If it is not null, print its double.

Challenge

  1. Declare String? middleName = 'Raza'; above main(). Inside main(), print Middle name: RAZA (upper case) only if a middle name exists.
  2. Declare Object value = 7;. If it is an int, print Square: …; if it is a String, print Length: ….
  3. Sara's cart total is 3500. Orders of 3000 or more get 10 percent off, and members (isMember = true) get 200 more off. Apply the discounts with two if statements and print Pay: ….

Practice Answers

Question 1 — Solution

dart
void main() {
  int age = 21;
  if (age >= 18) {
    print('Adult');
  }
}
output
Adult

Question 2 — Solution

dart
void main() {
  bool isWeekend = false;
  if (!isWeekend) {
    print('Go to school.');
  }
}
output
Go to school.

Question 3 — Solution

dart
void main() {
  int stock = 0;
  if (stock == 0) {
    print('Out of stock');
  }
  print('Checked');
}
output
Out of stock
Checked

Question 4 — Solution

dart
void main() {
  int marks = 45;
  if (marks >= 50) {
    print('Passed');
  }
  if (marks < 50) {
    print('Needs support');
  }
}
output
Needs support

Question 5 — Solution

dart
void main() {
  int price = 900;
  int balance = 1000;
  if (balance >= price) {
    balance -= price;
    print('Remaining: $balance');
  }
}
output
Remaining: 100

Question 6 — Solution

dart
void main() {
  double temperature = 18.0;
  if (temperature >= 15 && temperature <= 25) {
    print('Pleasant');
  }
}
output
Pleasant

Question 7 — Solution

dart
void main() {
  int? number = int.tryParse('42');
  if (number != null) {
    print(number * 2);
  }
}
output
84

Question 8 — Solution

dart
String? middleName = 'Raza';

void main() {
  var middle = middleName;
  if (middle != null) {
    print('Middle name: ${middle.toUpperCase()}');
  }
}
output
Middle name: RAZA

The local copy middle can be promoted; the top-level middleName cannot.

Question 9 — Solution

dart
void main() {
  Object value = 7;
  if (value is int) {
    print('Square: ${value * value}');
  }
  if (value is String) {
    print('Length: ${value.length}');
  }
}
output
Square: 49

Question 10 — Solution

dart
void main() {
  double total = 3500;
  bool isMember = true;
  if (total >= 3000) {
    total -= total * 0.10;
  }
  if (isMember) {
    total -= 200;
  }
  print('Pay: $total');
}
output
Pay: 2950.0

3500 minus 350 is 3150.0, and the member discount brings it to 2950.0.


Quick Revision

  1. What type must an if condition have?
  2. What happens when the condition is false?
  3. Why is if (score = 50) an error?
  4. What goes wrong with if (marks >= 50);?
  5. Why should you always use braces?
  6. What does if (age != null) let you do inside the block?
  7. Why doesn't if promote a top-level variable, and what is the fix?
  8. What does if (item is String) give you that as String does not?

Key Takeaways

  • An if statement runs its block only when its condition is true; otherwise it skips it.
  • The condition must be a bool — a comparison, a bool variable, or a &&/||/! expression. Numbers are not conditions.
  • A block in braces can hold many statements; always use braces.
  • Independent if statements 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) promotes x to T inside the block — a safe replacement for as.
  • A stray ; after the condition and missing braces are silent bugs; dart analyze catches 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.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.