Debugging
suggest changeDebugging Dart code comes down to a handful of tools:
printand small helpers for quick looks at values,assertto catch broken assumptions early,- reading stack traces, including async ones,
- the Dart VM service with DevTools or an IDE debugger for breakpoints, stepping and inspecting live objects,
dart:developerto trigger breakpoints and send objects to the debugger from code,dart analyze, which finds many bugs before you ever run the program.
The examples below were run with Dart 3.13. In stack traces, the long absolute path of the project has been shortened to file:///C:/app.
Print debugging done right
print is the fastest way to see what a program is doing. To make it useful, give your classes a toString. Without one you only get Instance of 'Point':
class Point {
final int x, y;
Point(this.x, this.y);
}
class Order {
final String id;
final List<String> items;
Order(this.id, this.items);
@override
String toString() => 'Order($id, items: $items)';
}
void main() {
final p = Point(1, 2);
final o = Order('A-17', ['apple', 'pear']);
print(p);
print(o);
print('runtimeType: ${o.runtimeType}, hash: ${identityHashCode(o)}');
final values = <Object?>[1, 1.0, '1', null, [1]];
for (final v in values) {
print('$v is ${v.runtimeType}');
}
}
Output:
Instance of 'Point'
Order(A-17, items: [apple, pear])
runtimeType: Order, hash: 147395723
1 is int
1.0 is double
1 is String
null is Null
[1] is List<int>
runtimeType tells you the actual type of a value, which is very helpful when a dynamic value from JSON isn't what you expected. identityHashCode tells you whether two variables refer to the same object (it is different from hashCode, which classes can override).
Records and classes from packages like freezed or equatable generate a readable toString for you.
A dbg helper
A small generic helper that prints a value with its source location, then returns it, lets you wrap any expression without restructuring the code. It writes to stderr so it doesn't mix with the program's real output:
import 'dart:io';
/// Prints [value] with the caller's file and line, then returns it.
T dbg<T>(T value, [String label = 'value']) {
final frame = StackTrace.current.toString().split('\n')[1];
final location = RegExp(r'\((.*)\)').firstMatch(frame)?.group(1) ?? '?';
final short = Uri.parse(location).pathSegments.last;
stderr.writeln('[$short] $label = $value');
return value;
}
int area(int w, int h) => dbg(w * h, 'area');
void main() {
final total = dbg([area(2, 3), area(4, 5)].reduce((a, b) => a + b), 'total');
print('result: $total');
}
Output:
[p2.dart:12:27] area = 6
[p2.dart:12:27] area = 20
[p2.dart:15:17] total = 26
result: 26
StackTrace.current captures the stack at the point of the call; frame #1 is the caller of dbg. The frame format is an implementation detail of the VM, so use this for debugging only, never for program logic.
For anything you want to keep in the code, use a real logger with levels instead of print (see Logging).
Assertions
assert(condition, [message]) throws an AssertionError when the condition is false. Assertions document assumptions and catch bugs close to their cause instead of far downstream:
class Account {
int balance;
Account(this.balance) : assert(balance >= 0, 'balance must not be negative');
void withdraw(int amount) {
assert(amount > 0, 'amount must be positive, got $amount');
balance -= amount;
}
}
void main() {
final a = Account(100);
a.withdraw(-5);
print('balance: ${a.balance}');
}
The important detail: assertions are disabled by default in dart run and in compiled executables. They are enabled by dart test, by Flutter debug builds, by the VS Code and IntelliJ debuggers, and by the --enable-asserts flag:
$ dart run bin/p3.dart
balance: 105
$ dart run --enable-asserts bin/p3.dart
Unhandled exception:
'file:///C:/app/bin/p3.dart': Failed assertion: line 6 pos 12: 'amount > 0': amount must be positive, got -5
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:67:4)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:49:5)
#2 Account.withdraw (file:///C:/app/bin/p3.dart:6:12)
#3 main (file:///C:/app/bin/p3.dart:13:5)
#4 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#5 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
Without the flag the bug goes unnoticed and the balance silently grows. Because assertions can be turned off, use them only for programmer errors. Validate user input and external data with real checks that throw ArgumentError, FormatException and so on (see Exceptions).
The expression inside assert is not evaluated at all when assertions are off, so it costs nothing in production. Never put side effects in it.
Reading stack traces
When an exception escapes main, the VM prints the error and a stack trace and exits with code 255. To get the trace of an exception you catch, add a second parameter to catch:
Map<String, int> parseScores(List<String> lines) {
final scores = <String, int>{};
for (final line in lines) {
final [name, score] = line.split('=');
scores[name] = int.parse(score);
}
return scores;
}
void main() {
try {
parseScores(['ann=10', 'bob=x7']);
} on FormatException catch (e, st) {
print('caught: $e');
print(st);
}
parseScores(['ann=10', 'bob']);
}
Output:
caught: FormatException: Invalid radix-10 number (at character 1)
x7
^
#0 int._handleFormatError (dart:core-patch/integers_patch.dart:150:5)
#1 int._parseRadix (dart:core-patch/integers_patch.dart:179:14)
#2 int._parse (dart:core-patch/integers_patch.dart:121:12)
#3 int.parse (dart:core-patch/integers_patch.dart:81:12)
#4 parseScores (file:///C:/app/bin/p4.dart:5:24)
#5 main (file:///C:/app/bin/p4.dart:12:5)
#6 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#7 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
Unhandled exception:
Bad state: Pattern matching error
#0 parseScores (file:///C:/app/bin/p4.dart:4:5)
#1 main (file:///C:/app/bin/p4.dart:17:3)
#2 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#3 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
How to read it:
- Frame
#0is where the error was thrown; each following frame is the caller of the previous one. - Skip the
dart:core-patchanddart:isolate-patchframes, which are SDK internals, and look for the first frame in your own code: hereparseScoresat line 5, column 24 (theint.parsecall). - The second error comes from a failed destructuring:
'bob'.split('=')has one element, so the pattern[name, score]doesn't match and Dart throws aStateError. The trace points at line 4, the declaration with the pattern.
In VS Code and IntelliJ the file:///...:line:column locations in the terminal are clickable.
Use catch (e, st) with logging, and Error.throwWithStackTrace(error, st) when you wrap an error and want to keep the original trace. A bare rethrow keeps the trace automatically.
Async stack traces
The VM keeps track of await chains, so a trace through async functions shows the whole path, with <asynchronous suspension> marking the points where a function was suspended:
import 'dart:async';
Future<String> fetchUser(int id) async {
await Future.delayed(const Duration(milliseconds: 10));
if (id < 0) throw ArgumentError.value(id, 'id', 'must be >= 0');
return 'user$id';
}
Future<String> loadProfile(int id) async {
final user = await fetchUser(id);
return 'profile of $user';
}
Future<void> main() async {
try {
await loadProfile(-1);
} catch (e, st) {
print(e);
print(st);
}
// Callback-style code loses the async chain:
Timer(const Duration(milliseconds: 1), () {
try {
throw StateError('inside timer');
} catch (e, st) {
print(e);
print(st);
}
});
}
Output:
Invalid argument (id): must be >= 0: -1
#0 fetchUser (file:///C:/app/bin/p5.dart:5:15)
<asynchronous suspension>
#1 loadProfile (file:///C:/app/bin/p5.dart:10:16)
<asynchronous suspension>
#2 main (file:///C:/app/bin/p5.dart:16:5)
<asynchronous suspension>
Bad state: inside timer
#0 main.<anonymous closure> (file:///C:/app/bin/p5.dart:24:7)
#1 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
#2 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:423:19)
#3 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:454:5)
#4 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
The await chain is complete. The timer callback, however, only shows the event loop that ran it: who scheduled the timer is lost. The same happens with Future.then callbacks, stream listeners and Completers.
Chained traces with package:stack_trace
package:stack_trace (dart pub add stack_trace) records where callbacks were registered. Run code inside Chain.capture and every error comes with a Chain, one trace per asynchronous step. terse folds SDK frames and shortens paths:
import 'dart:async';
import 'package:stack_trace/stack_trace.dart';
void scheduleWork() {
Timer(const Duration(milliseconds: 1), () {
throw StateError('inside timer');
});
}
void main() {
Chain.capture(() {
scheduleWork();
}, onError: (error, chain) {
print('error: $error');
print(chain.terse);
});
}
Output:
error: Bad state: inside timer
p6.dart 6:5 scheduleWork.<fn>
===== asynchronous gap ===========================
dart:async new Timer
p6.dart 5:3 scheduleWork
p6.dart 12:5 main.<fn>
package:stack_trace Chain.capture
p6.dart 11:9 main
Now you can see that scheduleWork created the timer. Chain capturing slows the program down, so enable it while debugging, not in production. Trace.format(st) from the same package formats a single StackTrace in the same compact style.
package:test uses chained traces automatically; turn them off with dart test --no-chain-stack-traces if they get in the way.
For errors that nobody catches (a failed future without a handler, an exception in a stream listener), use runZonedGuarded to see them all in one place. See "Catching uncaught errors" in Logging.
Debug-only code and build modes
Sometimes you want extra checks or output only while developing. Dart has no #ifdef, but compile-time constants give you the same effect, and the compiler removes code behind a false constant:
const bool isProduct = bool.fromEnvironment('dart.vm.product');
const bool verbose = bool.fromEnvironment('VERBOSE');
const String env = String.fromEnvironment('ENV', defaultValue: 'dev');
bool get assertsEnabled {
var enabled = false;
assert(enabled = true);
return enabled;
}
void main() {
print('product build: $isProduct');
print('asserts on: $assertsEnabled');
print('VERBOSE: $verbose');
print('ENV: $env');
if (verbose) print('extra diagnostics...');
}
Running it three ways:
$ dart run bin/p7.dart
product build: false
asserts on: false
VERBOSE: false
ENV: dev
$ dart run --enable-asserts -DVERBOSE=true -DENV=staging bin/p7.dart
product build: false
asserts on: true
VERBOSE: true
ENV: staging
extra diagnostics...
$ dart compile exe bin/p7.dart -o p7.exe && ./p7.exe
product build: true
asserts on: false
VERBOSE: false
ENV: dev
dart.vm.productistruein AOT-compiled executables (dart compile exe, see Compiling to executables).- The
assert(enabled = true)trick detects whether assertions are on, which is roughly "running in a debugger or tests". -Ddefines work withdart run,dart compileandflutter run.
In Flutter, use kDebugMode, kProfileMode and kReleaseMode from package:flutter/foundation.dart instead.
Using a debugger
A real debugger lets you stop at a line, step through the code, look at all local variables and evaluate expressions in the paused frame. Dart's debugger is built into the VM and is exposed through the VM service protocol; IDEs and DevTools are clients of it.
VS Code and IntelliJ
With the Dart (or Flutter) extension in VS Code, click in the gutter to set a breakpoint and press F5. To pass arguments or flags, create .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "server",
"type": "dart",
"request": "launch",
"program": "bin/server.dart",
"args": ["--port", "8080"],
"toolArgs": ["-DVERBOSE=true"],
"env": { "DB_URL": "postgres://localhost/dev" },
"console": "terminal"
}
]
}
args go to your program, toolArgs go to the dart command. "console": "terminal" runs the program in the integrated terminal so it can read from stdin.
Useful debugger features that are easy to miss:
- Conditional breakpoints: right-click a breakpoint and enter an expression like
id == 42; it only stops when the condition is true. - Logpoints: a breakpoint that prints a message such as
user = {user}instead of stopping. It's print debugging without editing the code. - Break on exceptions: in the Breakpoints panel, choose to pause on uncaught or on all exceptions. Stopping at the throw site shows the variables that caused the error.
- Debug Console: evaluate any Dart expression in the context of the paused frame, for example
items.where((e) => e.price > 10).toList(). - Debug my code only: by default the debugger doesn't step into SDK and package sources; enable "Debug SDK libraries" / "Debug external package libraries" in settings when you need to.
IntelliJ IDEA and Android Studio offer the same features through their Dart plugin.
DevTools from the command line
Without an IDE, start the program with --observe. The VM prints the address of the VM service and of DevTools, which you open in a browser:
$ dart run --observe bin/main.dart
The Dart VM service is listening on http://127.0.0.1:8181/N8GMNdh6vjA=/
The Dart DevTools debugger and profiler is available at: http://127.0.0.1:8181/N8GMNdh6vjA=/devtools/?uri=ws://127.0.0.1:8181/N8GMNdh6vjA=/ws
--observe does not turn on assertions, so add --enable-asserts if you want them. Useful variations:
--observe=0picks a free port instead of 8181.--pause-isolates-on-startstops beforemainruns, so you have time to set breakpoints in DevTools.--pause-isolates-on-exitkeeps the process alive at the end so you can inspect memory or the CPU profile.--pause-isolates-on-unhandled-exceptionsstops at the throw site of an uncaught exception.
The DevTools Debugger page has breakpoints, stepping and a console. The other pages help with performance problems: CPU Profiler for slow code, Memory for leaks and allocation, Network for HTTP traffic made with dart:io (see Memory and garbage collection). You can also attach VS Code to a running VM service with an "request": "attach" configuration and the service URI.
Debugging tests
dart test runs each test file in its own isolate. To debug one test, select it by name and pause before tests run:
dart test test/parser_test.dart -n "parses empty input" --pause-after-load
The test runner prints the VM service and DevTools URLs and waits until you resume. In VS Code it's simpler: click "Debug" above a test(...) call.
Breakpoints and inspection from code: dart:developer
dart:developer lets the program talk to an attached debugger:
import 'dart:developer';
class Cart {
final items = <String, int>{};
void add(String name, int qty) {
items.update(name, (q) => q + qty, ifAbsent: () => qty);
}
}
void main() {
final cart = Cart()..add('apple', 2)..add('pear', 1);
inspect(cart); // shows the object in DevTools
debugger(when: cart.items.length > 1, message: 'cart has several items');
cart.add('apple', 3);
print(cart.items);
}
debugger()is a programmatic breakpoint. Withwhen:it acts like a conditional breakpoint whose condition can be any Dart code, which is handy for conditions too complex for the IDE.inspect(object)sends the object to the DevTools inspector and returns it, so you can wrap an expression with it.log()sends structured messages to the DevTools Logging view (covered in Logging).
Run with --observe or from an IDE and the program stops at debugger:
vm-service: isolate (3955279244635999) 'main' has no debugger attached and is paused. Connect to the Dart VM service at http://127.0.0.1:8181/N8GMNdh6vjA=/ to debug.
Don't commit debugger() calls. In a JIT run (dart run bin/main.dart or dart bin/main.dart) the isolate pauses at debugger() even with no debugger attached and no VM service message, so the program looks like it hangs. In an AOT executable built with dart compile exe, debugger() and inspect() do nothing and the same program prints {apple: 5, pear: 1}.
Let the analyzer find bugs first
Many bugs that need a debugger in other languages are caught by dart analyze before the program runs. Stricter settings in analysis_options.yaml catch more:
analyzer:
language:
strict-casts: true
linter:
rules:
- unawaited_futures
With this code:
import 'dart:io';
Future<void> save(String path, String data) async {
await File(path).writeAsString(data);
}
int parseCount(Map<String, dynamic> json) {
int count = json['count'];
return count * 2;
}
Future<void> main() async {
save('out.txt', 'hello');
print(parseCount({'count': 3}));
}
dart analyze reports:
Analyzing an...
error - bin\main.dart:8:15 - A value of type 'dynamic' can't be assigned to a variable of type 'int'. Try changing the type of the variable, or casting the right-hand type to 'int'. - invalid_assignment
info - bin\main.dart:13:3 - Missing an 'await' for the 'Future' computed by this expression. Try adding an 'await' or wrapping the expression with 'unawaited'. - unawaited_futures
2 issues found.
strict-caststurns the implicit cast fromdynamicinto an error. Without it, a JSON value of the wrong type only fails at runtime with aTypeError.unawaited_futurescatches a forgottenawait. A missingawaitis one of the most common sources of confusing async bugs: errors that are never reported and operations that finish in the "wrong" order.
The lints and flutter_lints packages give you a good base set of rules (see Common pitfalls for more bugs worth knowing about).
A debugging checklist
- Reproduce the bug reliably, ideally as a failing test. A test turns a debugging session into a fast loop and keeps the bug from coming back.
- Read the whole error message and stack trace. Find the first frame in your code.
- Run with assertions on (
--enable-asserts, or just run underdart testor the IDE). - Check types at the boundaries: values from JSON,
dynamicand casts are frequent culprits. PrintruntimeType. - Look for a missing
awaitwhen things happen out of order or errors disappear. - Stop at the throw site with "break on exceptions" or
--pause-isolates-on-unhandled-exceptions, and inspect the local variables. - Narrow it down: bisect the input, or use
git bisectto find the commit that introduced the bug.
Summary
- Give classes a
toStringand useruntimeTypeto make printed values informative; a smalldbghelper adds source locations. assertis off by default indart runand compiled executables. Use--enable-asserts; tests and IDE debug sessions enable it automatically.- Use
catch (e, st)to get stack traces; read them from the first frame in your own code. awaitchains show up in traces as<asynchronous suspension>; for callbacks and timers useChain.capturefrompackage:stack_trace.bool.fromEnvironment('dart.vm.product'),-Ddefines and theasserttrick let you write debug-only code.- Debug with breakpoints in VS Code or IntelliJ, or with
dart run --observeand DevTools;--pause-isolates-on-startanddart test --pause-after-loadgive you time to attach. debugger()andinspect()fromdart:developercontrol the debugger from code. Remove them before committing, sincedebugger()pauses a JIT run even without a debugger.- Strict analyzer settings and lints such as
unawaited_futurescatch many bugs before you run anything.