Sub topic 6
Pausing code with breakpoints and stepping
This chapter covers the DevTools debugger: how to pause a running Flutter app, inspect its state, and move through code one step at a time. It assumes you can read Dart, know how async and await work, and can run a Flutter app on an emulator, simulator, or device. It also assumes you can open DevTools and connect it to a running app, as covered earlier in this tutorial.
Why pause the app
Logging tells you what happened. A breakpoint lets you stop the app at a chosen line and look at everything in scope at that moment. You can read local variables, evaluate expressions, and see the chain of calls that led to the line.
Use a breakpoint when you need to answer questions such as:
- Why does this variable hold a value I did not expect?
- Which caller invoked this function with bad arguments?
- Which branch of an
ifactually ran?
Logging fits better when you want a long history of events. A breakpoint fits better when you want a detailed view of one moment.
Where the debugger runs
You can debug in two places. Both use the same Dart VM service, so they behave alike.
- Your IDE. VS Code and Android Studio have built-in debuggers. Gutter breakpoints, the Variables panel, and the call stack all work there.
- The DevTools Debugger tab. In a browser DevTools window, the Debugger view shows a file list, a source pane, and panels for call stack, variables, and breakpoints. Depending on how you launched DevTools, this tab may be hidden when it is embedded in an IDE that already provides debugging.
Pausing requires debug mode. Profile and release builds do not support breakpoints, because the Dart code is compiled ahead of time and the VM service does not offer the same debugging features. Start the app with a plain flutter run, or press the debug button in your IDE.
# Debug mode is the default
flutter runSetting breakpoints
A breakpoint is a marker on a line of code. When execution reaches that line, the app pauses before running it.
In the DevTools Debugger view:
- Open the file from the file list, or press Ctrl+P (Cmd+P on macOS) and type part of the file name.
- Click the line number in the gutter. A marker appears.
- Trigger the code path in the app. The app freezes and the line is highlighted.
Click the marker again to remove the breakpoint. The Breakpoints panel lists all breakpoints and lets you toggle or delete them.
While paused, the app's UI does not respond. Animations stop and taps are ignored, because the UI isolate is stopped. Resuming restores normal behavior.
Breakpoints in the code itself
You can also pause from code with debugger() from dart:developer. It only pauses when a debugger is attached, so it does nothing in a release build. The when argument makes it conditional.
import 'dart:developer';
double applyDiscount(double total, double discount) {
final result = total - discount;
// Pause the app in the debugger only when the unexpected case happens.
debugger(when: result < 0, message: 'Negative total');
return result;
}This is useful when the bug appears only in rare cases. Clicking a gutter breakpoint would pause on every call, including thousands of good ones. A conditional debugger() pauses only on the bad one.
Remove these calls before shipping. They are harmless at runtime without a debugger, but they are noise in the code.
Reading the paused state
When the app pauses, three panels matter most.
| Panel | What it shows | Typical use |
|---|---|---|
| Call stack | The chain of function calls that led to the paused line | Find out who called this code |
| Variables | Locals, arguments, and `this` fields in the selected frame | Check values and object state |
| Breakpoints | All breakpoints, with toggles | Disable breakpoints without deleting them |
Click a different frame in the call stack and the Variables panel switches to that frame's scope. This is how you move up from the failing line to the caller and check which argument was wrong.
Evaluating expressions
The debug console accepts Dart expressions and evaluates them in the scope of the selected frame. While paused in applyDiscount, you can type:
total - discountand see the result. You can also call methods on objects, for example items.where((i) => i.isEmpty).length. Keep in mind:
- Evaluation can have side effects. Calling a method that changes state changes the real app.
- Variables the compiler optimized away may show as unavailable. In debug mode this is rare.
- You can evaluate in any frame, not just the top one.
Stepping
After a pause, stepping lets you advance execution in small controlled moves. The controls appear in the debugger toolbar.
| Control | What it does | Use it when |
|---|---|---|
| Resume | Runs until the next breakpoint or the app ends | You have seen enough |
| Step over | Runs the current line and stops on the next line in the same function | You do not care about the internals of a call |
| Step in | Enters the function called on the current line | You suspect the called function |
| Step out | Runs until the current function returns, then stops in the caller | You entered a function by mistake or finished checking it |
A common loop is: pause, read variables, step over a few lines, and watch which value changes. When a value becomes wrong after a line, step back to that line next time and use step in.
Stepping through async code
Dart async functions pause at each await. Stepping over an await line runs the awaited future to completion in the background, then stops on the next line after the future resolves. The debugger follows the logical flow of the function, so you do not land in the event loop.
import 'dart:developer';
Future<List<String>> loadNames(Future<List<String>> Function() fetch) async {
final raw = await fetch(); // Step over: waits for the future
final cleaned = raw.where((n) => n.trim().isNotEmpty).toList();
debugger(when: cleaned.isEmpty, message: 'No names after cleaning');
return cleaned;
}Two points are worth knowing:
- While the app is paused, timers and microtasks on that isolate are also paused. A timeout may fire immediately after you resume because wall-clock time passed while you were stopped.
- The call stack for async code can include "asynchronous gap" markers. These show where an
awaitsplit the stack, and the frames beyond them are reconstructed from the future chain, so they are usually still useful.
Pausing on exceptions
You do not always know the line where a bug occurs. Exception breakpoints pause the app at the point where an exception is thrown.
The usual options are:
- Uncaught exceptions only. Pause when nothing will handle the error. This is the default in most setups and is the least noisy.
- All exceptions. Pause on every throw, including ones that a
tryblock catches. This can be very noisy, since libraries sometimes throw and catch internally.
In DevTools, use the exception pause setting in the debugger toolbar. If you choose all exceptions and the app stops constantly, switch back to uncaught only and add a targeted breakpoint instead.
This approach is especially helpful for errors that Flutter catches and prints as a red screen or console message. Flutter's framework catches exceptions in build and reports them with FlutterError. They may not count as uncaught, so choose "all exceptions" temporarily when a framework error leaves you without a useful line number.
Debugging a realistic example
Suppose a cart screen shows a negative total after a coupon is applied. The relevant code is:
import 'package:flutter/material.dart';
class CartModel extends ChangeNotifier {
final List<double> _prices = [];
double _discount = 0;
double get total {
final sum = _prices.fold<double>(0, (a, b) => a + b);
return sum - _discount;
}
void add(double price) {
_prices.add(price);
notifyListeners();
}
void applyCoupon(double amount) {
_discount = amount;
notifyListeners();
}
}A workflow for finding the cause:
- Set a breakpoint on the
return sum - _discount;line. - Add an item, then apply the coupon in the running app. The app pauses.
- Read
sumand_discountin the Variables panel. Ifsumis 0 and_discountis 10, the coupon was applied before any item was added, and nothing stops the total from going negative. - Click the caller frame in the call stack. You find
applyCouponwas called from a button handler with no check on the cart contents. - Fix the logic, for example by clamping the total at zero, then hot reload and repeat the steps.
double get total {
final sum = _prices.fold<double>(0, (a, b) => a + b);
final result = sum - _discount;
return result < 0 ? 0 : result;
}Because the cause was found by reading state, not by guessing, the fix targets the real problem.
Common problems
- The breakpoint never hits. The code may not run on your path, or the file you opened differs from the one in the running app. Confirm the app was started in debug mode and that you hot restarted after large edits.
- The breakpoint appears grayed out. The line may not be executable, such as a comment, a blank line, or a declaration. Move it to a line with a statement.
- Line numbers look off after edits. Hot reload usually updates breakpoints, but a full restart is the safe fix when the debugger and source disagree.
- A timeout or network call fails right after resuming. Time kept passing while you were paused. Reproduce again with fewer pauses, or use logging for time-sensitive code.
- Pausing inside
buildfreezes the screen.buildruns often, so an unconditional breakpoint there pauses over and over. Use a conditional breakpoint ordebugger(when: ...).
Choosing between logging and breakpoints
| Situation | Better tool |
|---|---|
| Need a history of many events | Logging |
| Need to inspect one failing moment in detail | Breakpoint |
| Bug depends on timing | Logging, since pausing changes timing |
| Need to call methods or test an expression on live objects | Breakpoint with the debug console |
| Code runs very often and the bug is rare | Conditional `debugger()` |
The two tools complement each other. A common pattern is to find the rough area with logs, then place a breakpoint at the point the logs identify.
Summary
- Breakpoints require debug mode.
- Set them in the gutter, or in code with
debugger(when: ...). - Read the call stack and Variables panel to understand the paused moment, and use the debug console to evaluate expressions.
- Step over, step in, and step out move you through code in small steps. Resume continues normal execution.
- Pause on uncaught exceptions by default, and use all exceptions only briefly.
- Use conditional pauses for code that runs often.
Exercise
A build method runs many times per second, and you only want to inspect it when items.length is 0. Which approach avoids pausing on every build, and why does it matter?
Show answer
Use a conditional breakpoint with the condition items.length == 0, or call debugger(when: items.isEmpty) inside build. An unconditional breakpoint would pause on every build, freezing the app repeatedly and making it hard to reach the one case you care about. The conditional form pauses only in the case you want to examine.
Exercise
You are paused on the line final data = await repository.load();. You want to see the result of the call without entering load. Which stepping control do you use, and where does execution stop next?
Show answer
Use step over. The call to load runs and the await completes. Execution then stops on the next line after the await in the same function, with data available in the Variables panel.
Exercise
Why can a breakpoint make a network timeout bug harder to reproduce, and what is a better way to investigate it?
Show answer
While the app is paused, real time keeps passing, so timers and timeouts can expire immediately after you resume. That changes the behavior you wanted to observe. Use logging with timestamps, which does not stop the app, and place a breakpoint only after the logs show where the problem begins.