On this page11 sections
Lecture 053: assert Statements
| Day | Extra Topics |
| Lecture | 053 of 057 |
| Estimated video length | 8 min |
| Target | Dart 3.12 |
| Level | Beginner |
An
assertis a note to yourself that says "this must be true here". While you're developing, Dart checks it and stops loudly if it's false, so you catch the bug early. In the finished app, asserts are switched off and cost nothing.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 015–016 (if), 030–032 (classes and constructors) and 037 (exceptions).
Learning Objectives
- Write an
assertwith and without a message - Know when asserts run and when they are ignored
- Turn asserts on with
--enable-asserts - Use asserts in constructors
- Choose between
assertand a real check withthrow
1. Writing an assert
assert(condition);
assert(condition, 'message shown when it fails');double average(List<int> marks) {
assert(marks.isNotEmpty, 'marks must not be empty');
return marks.reduce((a, b) => a + b) / marks.length;
}If the condition is true, nothing happens. If it's false (and asserts are on), the program
stops with an AssertionError.
2. When Do Asserts Run?
This surprises almost everyone: a plain dart run ignores asserts.
| How the code runs | Asserts checked? |
|---|---|
dart run main.dart | no |
dart run --enable-asserts main.dart | yes |
Flutter app in debug mode (flutter run) | yes |
| Flutter release build | no |
Running the average example with asserts on:
void main() {
print(average([80, 90, 100]));
print(average([]));
}$ dart run --enable-asserts main.dart
90.0
Unhandled exception:
'file:///.../main.dart': Failed assertion: line 2 pos 10: 'marks.isNotEmpty': marks must not be emptyWithout --enable-asserts, the same program skips the check and crashes one line later with a
much less helpful message:
90.0
Unhandled exception:
Bad state: No elementThe assert pointed straight at the real problem.
3. Asserts in Constructors
Put asserts after a : in a constructor to check the values an object is created with:
class Rectangle {
final double width, height;
Rectangle(this.width, this.height)
: assert(width > 0, 'width must be positive'),
assert(height > 0, 'height must be positive');
}Flutter's own widgets are full of asserts like this. That's why a wrong value often gives you a clear red error while you're developing.
4. assert vs a Real Check
Asserts disappear in release builds, so never rely on them for things that can really go
wrong at runtime (bad user input, a missing file, no internet). Use if and throw for those
(Lecture 037).
Use assert for… | Use if + throw for… |
|---|---|
| your own programming mistakes | problems that can happen in real use |
| "this should be impossible" | invalid input from users or the network |
| checks you only want while developing | checks that must always run |
Code Examples
Example 1: Catching a Bug in a Bank Account
class BankAccount {
double _balance = 0;
double get balance => _balance;
void deposit(double amount) {
assert(amount > 0, 'deposit amount must be positive, got $amount');
_balance += amount;
assert(_balance >= 0, 'balance can never go negative');
}
}
void main() {
var account = BankAccount();
account.deposit(500);
print('Balance: ${account.balance}');
account.deposit(-200);
print('Balance: ${account.balance}');
}Output with dart run --enable-asserts main.dart
Balance: 500.0
Unhandled exception:
'file:///.../main.dart': Failed assertion: line 6 pos 12: 'amount > 0': deposit amount must be positive, got -200.0Output with a plain dart run main.dart
Balance: 500.0
Balance: 300.0With asserts off, the bug slips through silently and the balance drops. During development,
always run with asserts on. And if deposits come from users, add a real if check as well.
Common Beginner Mistakes
1. "My assert does nothing!": you ran dart run without --enable-asserts. Asserts are
off by default outside Flutter's debug mode.
2. Validating user input with assert: the check vanishes in the release app. Use if and
throw (or show an error message).
3. Putting important work inside an assert: assert(saveFile()); never calls saveFile()
when asserts are off. An assert should only check, never do.
4. Writing the condition backwards: the condition is what should be true:
assert(age >= 0), not assert(age < 0).
Practice Questions
- What happens when an assert's condition is
true? - Does
dart run main.dartcheck asserts? - Write an assert that checks
quantityis at least 1, with a message. - Should a login form check "password not empty" with
assert? Why? - Where else, besides inside a method, can you write an assert?
Practice Answers
- Nothing. The program continues.
- No. Add
--enable-asserts. assert(quantity >= 1, 'quantity must be at least 1');- No. Asserts are removed in release builds; user input needs a check that always runs.
- In a constructor, after the
:.
Key Takeaways
assert(condition, 'message')stops the program if the condition is false.- Asserts run only with
--enable-assertsor in Flutter debug mode. - Use them to catch your own mistakes early, often in constructors.
- Never use asserts for user input or anything that must be checked in the real app.