Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 61 ยท Errors and Libraries

Assertions and Debugging

Learn how to find Dart bugs faster: assert statements and debug mode, print debugging, the debugger, DevTools, logging with levels and stack traces.

Exceptions tell you what went wrong while a program runs. Assertions and debugging tools help you find out why, ideally before anyone else sees the bug. An assertion is a sanity check that says "this must be true here"; if it is not, the program stops right at the mistake instead of limping on and failing somewhere far away.

This lesson covers assert, the difference between debug and release builds, print debugging done well, the interactive debugger, Dart DevTools and the idea behind logging with levels. Real Dart and tool output are shown as read-only text; two TypeScript stand-ins let you try the ideas.

assert

assert(condition) checks a Boolean expression. If it is false, Dart throws an AssertionError. You can add a message as a second argument:

DART
double averageOf(List<int> values) {
  assert(values.isNotEmpty, 'averageOf needs at least one value');
  return values.reduce((a, b) => a + b) / values.length;
}

void main() {
  print(averageOf([2, 4, 6]));   // 4.0
  print(averageOf([]));          // AssertionError in debug mode
}

In debug mode the second call stops with an error similar to:

TEXT
Unhandled exception:
'package:app/main.dart': Failed assertion: line 2 pos 10: 'values.isNotEmpty':
averageOf needs at least one value

The crucial rule: assertions only run in debug mode. For command-line programs, pass --enable-asserts to be sure they run (dart run --enable-asserts bin/main.dart); Flutter debug builds enable them automatically; compiled release builds (dart compile exe, Flutter release) remove them completely. That has two consequences.

  • Assertions are free in production, so you can be generous with them while developing.
  • They are never a substitute for validating input. User data, files and network responses must be checked with normal if statements and real exceptions, because an assertion will not run in the shipped app.

An assertion must not have side effects either, since removing it must not change the program's behavior. assert(queue.removeFirst() != null) would delete an element only in debug mode.

Good targets for assertions are conditions that your own code guarantees: an internal list is sorted, an index is in range after your own computation, a value was initialized before the call. Constructor initializer lists can use them too, which is common in Flutter packages:

DART
class Rectangle {
  const Rectangle(this.width, this.height)
      : assert(width >= 0, 'width must not be negative'),
        assert(height >= 0, 'height must not be negative');

  final double width;
  final double height;
}

Because the constructor is const, the assertion is even checked at compile time for constant arguments.

flowchart LR
    D["Debug / JIT run<br/>with asserts enabled"] --> A{"assert condition"}
    A -->|"true"| OK["Program continues"]
    A -->|"false"| AE["AssertionError<br/>at the exact line"]
    R["Release / AOT build"] --> S["assert removed:<br/>never evaluated"]

Assertions guard development builds only; release builds skip them entirely.

TypeScript Debug-only checks (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The simplest tool is print. It is quick and works everywhere, and there is nothing wrong with it as long as you use it deliberately:

  • Print the variable and its value, not just a marker: print('total = $total'); beats print('here 2');.
  • Use print('${items.length} items: $items') to see whole collections; lists, maps and records have readable toString output.
  • Print runtimeType when you suspect the wrong type arrives: print(value.runtimeType);.
  • Print StackTrace.current to learn who called a function: print(StackTrace.current);.
  • Remove the prints when you are done, or turn them into proper logging.

In Flutter, debugPrint throttles long output so the system log does not drop lines, and dart:developer offers log(message, name: 'Cart', error: e), which shows up in DevTools with structure. Also remember that print goes to standard output, so in a command-line program it can mix with the program's real output. For diagnostics you can send text to standard error instead: stderr.writeln('debug: ...'); from dart:io.

The debugger

A debugger lets you pause the program and look around, which beats guessing. In VS Code or IntelliJ/Android Studio:

  1. Click in the margin next to a line to set a breakpoint.
  2. Start the program in debug mode (VS Code: Run and Debug, or F5).
  3. When execution stops, inspect the variables panel, hover over expressions and use the debug console to evaluate code in the current scope.
  4. Step over runs the current line, step into enters the function being called, step out finishes the current function.
  5. Use conditional breakpoints (for example index == 41) and logpoints (print without editing the code) to avoid stopping on every loop pass.

You can also stop programmatically with debugger(); from dart:developer. It does nothing unless a debugger is attached, and you can pass a condition: debugger(when: total < 0, message: 'negative total');. Treat it like a temporary breakpoint and remove it before committing.

When the program crashes, read the stack trace from the top: the first lines show where the exception was thrown, and the lines below show who called it. Look for the first frame that points at your own code (package:your_app/...), because that is usually where the fix belongs.

Dart DevTools

DevTools is a suite of browser-based tools that ships with the SDK. Run dart devtools, or open it from your IDE while debugging, and you get:

  • Inspector (Flutter): the widget tree and its properties.
  • Performance and CPU profiler: where time goes, as flame charts.
  • Memory: allocations, snapshots and leak hunting.
  • Network: requests made through dart:io and Flutter.
  • Logging: output from print, dart:developer log and framework events.
  • Debugger: breakpoints and a source view, just like the IDE.

Reach for DevTools when the question is "why is this slow?" or "why does memory keep growing?". For plain logic errors, breakpoints and assertions are usually quicker.

Logging with levels

Scattered print calls become noise in a larger program. A logger adds a severity (such as debug, info, warning, error), a name for the part of the program and a timestamp, and lets you filter output by level. The official package:logging follows this design:

DART
import 'package:logging/logging.dart';

final log = Logger('Checkout');

void main() {
  Logger.root.level = Level.INFO;                 // hide FINE and below
  Logger.root.onRecord.listen((record) {
    print('${record.level.name} ${record.loggerName}: ${record.message}');
  });

  log.fine('Cart loaded');                        // hidden
  log.info('Order 17 placed');                    // shown
  log.severe('Payment failed', Exception('card declined'));
}
TEXT
INFO Checkout: Order 17 placed
SEVERE Checkout: Payment failed

The point is the structure: libraries log freely, and the application decides what to show and where to send it (console, file, a crash-reporting service). Packages are explained in Libraries, Imports and Packages.

TypeScript A tiny leveled logger (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A debugging routine

When a bug appears, work through these steps:

  1. Reproduce it reliably, with the smallest input that shows the problem.
  2. Read the error message and stack trace fully before changing anything.
  3. Form a guess about the cause, then check it with an assertion, a print or a breakpoint.
  4. Fix the cause, not the symptom, and add a test that would have caught it.
  5. Keep the useful assertions and logs; remove the throwaway prints.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does an assert run?

    Assertions are checked in debug mode and removed from release builds, so they must not replace real validation.
  2. 2. Which use of assert is a mistake?

    The removal would run only in debug mode. Assertions must not have side effects, because the release build removes them.
  3. 3. What error does a failed assertion throw?

    A failed assert throws an AssertionError, which is an Error, not an Exception.
  4. 4. What does debugger() from dart:developer do?

    debugger() acts like a programmatic breakpoint. Without an attached debugger, it does nothing.
  5. 5. What is the main advantage of a logger over scattered print calls?

    Structured logging lets libraries log freely while the application decides which levels to show and where to send them.

Summary

  • assert(condition, message) throws an AssertionError in debug mode and is removed from release builds; never use it to validate external input.
  • Assertions must be free of side effects and are ideal for internal guarantees and const constructors.
  • Good print debugging shows names and values; debugger(), breakpoints, logpoints and stack traces give more control.
  • DevTools covers profiling, memory, network and logging.
  • A leveled logger such as package:logging replaces ad hoc prints in larger programs.

Next, organize code across files and share it with others in Libraries, Imports and Packages.