On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Writing an assert
  4. 2. When Do Asserts Run?
  5. 3. Asserts in Constructors
  6. 4. assert vs a Real Check
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 053: assert Statements

DayExtra Topics
Lecture053 of 057
Estimated video length8 min
TargetDart 3.12
LevelBeginner

An assert is 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 assert with 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 assert and a real check with throw

1. Writing an assert

dart
assert(condition);
assert(condition, 'message shown when it fails');
dart
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 runsAsserts checked?
dart run main.dartno
dart run --enable-asserts main.dartyes
Flutter app in debug mode (flutter run)yes
Flutter release buildno

Running the average example with asserts on:

dart
void main() {
  print(average([80, 90, 100]));
  print(average([]));
}
code
$ 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 empty

Without --enable-asserts, the same program skips the check and crashes one line later with a much less helpful message:

code
90.0
Unhandled exception:
Bad state: No element

The 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:

dart
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 mistakesproblems that can happen in real use
"this should be impossible"invalid input from users or the network
checks you only want while developingchecks that must always run

Code Examples

Example 1: Catching a Bug in a Bank Account

dart
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

code
Balance: 500.0
Unhandled exception:
'file:///.../main.dart': Failed assertion: line 6 pos 12: 'amount > 0': deposit amount must be positive, got -200.0

Output with a plain dart run main.dart

code
Balance: 500.0
Balance: 300.0

With 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

  1. What happens when an assert's condition is true?
  2. Does dart run main.dart check asserts?
  3. Write an assert that checks quantity is at least 1, with a message.
  4. Should a login form check "password not empty" with assert? Why?
  5. Where else, besides inside a method, can you write an assert?

Practice Answers

  1. Nothing. The program continues.
  2. No. Add --enable-asserts.
  3. assert(quantity >= 1, 'quantity must be at least 1');
  4. No. Asserts are removed in release builds; user input needs a check that always runs.
  5. In a constructor, after the :.

Key Takeaways

  • assert(condition, 'message') stops the program if the condition is false.
  • Asserts run only with --enable-asserts or 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.