Debugging Dart
Prerequisites: Testing with package:test
Debugging is finding out why code doesn't do what you expect.
1. Let the analyzer help
The Dart analyzer reports errors and warnings as you type. Read the
first problem — later ones are often caused by it — and use the
editor's quick fix (Ctrl + . / ⌘.) for suggested corrections. Run
dart analyze to check a whole project.
2. Read the stack trace
Unhandled exception:
Null check operator used on a null value
#0 OrderService.total (package:shop/order_service.dart:12:31)
#1 main (file:///app/bin/shop.dart:20:3)
Read it top to bottom: the error, then where it happened
(order_service.dart, line 12, in OrderService.total), then the caller
(line 20, in main). Look for the first line from your code.
3. print and debugPrint
Printing values at key points often finds the problem fast. In Flutter,
use debugPrint, which avoids log lines being dropped when there are
many.
4. The debugger
Click next to a line number in VS Code or Android Studio to set a breakpoint, then start with Run → Start Debugging (F5). When execution pauses, you can:
- Inspect every variable.
- Step over (F10) to the next line, or step into (F11) a function.
- Evaluate expressions in the Debug Console.
Right-click a breakpoint to add a condition — invaluable inside loops.
5. assert
assert checks an assumption during development:
void setVolume(int level) {
assert(level >= 0 && level <= 10, 'Volume must be 0-10, got $level');
// ...
}
Asserts run in debug mode (dart run --enable-asserts, and Flutter debug
builds) and are removed from release builds. For checks that must always
run, throw an ArgumentError instead.
Flutter DevTools
Dart DevTools — opened from your editor — adds a widget inspector, performance timeline, memory view, and network inspector for Flutter and Dart apps.
A debugging process
- Reproduce the problem reliably — ideally as a failing test.
- Narrow it down: inspect values halfway through, and keep halving.
- Question assumptions — "this can't be null" is often exactly the problem.
- Fix it and keep the test, so the bug can't come back.