Sub topic 6
Avoiding accidental captures in closures
This chapter assumes you know Isolate.run and compute, and that you have read the previous chapter on what can be sent between isolates. Here you will learn how a closure you pass to an isolate can pull in far more than you wrote, and how to stop that from happening.
What a closure carries with it
Isolate.run takes a closure, which is a function that can see variables from the place where it was written. To run that closure in a new isolate, Dart has to copy the closure into the new isolate's separate heap. The copy includes everything the closure can reach: the variables it uses and the objects those variables point to.
The code you wrote is only part of what gets copied. The closure also carries a reference to its surrounding scope. This produces two failure modes:
- A crash. The reachable graph contains an object that cannot be sent, such as a
ReceivePort, a socket, or a FlutterBuildContext. The call fails with an error. - A slowdown. The graph is sendable but large. Dart copies all of it, and your "background" work starts with a long copy on the calling isolate.
The first failure is loud. The second is easy to miss, because everything still works.
The hidden `this`
Inside an instance method, any use of a field or another instance method means the closure uses this. You do not have to write this. Writing values instead of this.values has the same effect.
import 'dart:isolate';
int sumList(List<int> values) => values.fold(0, (a, b) => a + b);
class Tally {
Tally(this.values) : inbox = ReceivePort();
final List<int> values;
final ReceivePort inbox; // a ReceivePort cannot be sent to another isolate
// The closure reads `values`, which is `this.values`, so it captures `this`.
// `this` reaches `inbox`, so sending the closure fails.
Future<int> totalBad() => Isolate.run(() => sumList(values));
// Copy the field into a local first. The closure now captures only `data`.
Future<int> totalGood() {
final data = values;
return Isolate.run(() => sumList(data));
}
}
Future<void> main() async {
final tally = Tally([1, 2, 3]);
try {
print(await tally.totalBad());
} catch (e) {
print('totalBad failed: ${e.runtimeType}');
}
print(await tally.totalGood());
tally.inbox.close(); // an open ReceivePort would keep the program alive
}When you run this, totalBad fails with an error (typically an ArgumentError). Its message says the object is unsendable. totalGood prints 6.
The two methods contain almost the same text. The only difference is which variables the closure mentions, and that decides what is copied.
Fix 1: copy fields into locals
The pattern in totalGood is the most common fix. Before calling Isolate.run, read each field you need into a final local variable. Then use only those locals inside the closure.
Check for these cases, because each one captures this:
- A field read, such as
valuesor_cache. - A call to an instance method, such as
_parse(x), even without a visiblethis. - A call to a getter that depends on instance state.
- A nested closure that does any of the above.
A local variable is not an instance member, so using it does not pull in this. A parameter of the method also counts as a local.
Fix 2: pass work through a top-level or static function
The cleanest approach keeps the isolate's work out of the class entirely. Write a top-level function (or a static method) that takes everything it needs as arguments. The closure then holds only the arguments.
import 'dart:isolate';
class Job {
Job(this.name, this.numbers);
final String name;
final List<int> numbers;
}
// Top-level function: no `this`, no surrounding instance.
int _sumOfSquares(List<int> numbers) {
var total = 0;
for (final n in numbers) {
total += n * n;
}
return total;
}
// A small wrapper function keeps the closure's scope clean.
Future<int> runSumOfSquares(List<int> numbers) {
return Isolate.run(() => _sumOfSquares(numbers));
}
Future<void> main() async {
final job = Job('squares', [1, 2, 3, 4]);
print('${job.name}: ${await runSumOfSquares(job.numbers)}');
}The wrapper function runSumOfSquares is worth the extra lines. Dart allocates closure variables in a context, which is an object that holds the captured variables of a scope. Closures created in the same scope can share one context. If you write the isolate closure in a large method that has other closures and locals, the isolate closure may reach more than the variables it uses. A small dedicated function has a small scope, so there is little to over-capture.
Copies, not shared variables
Whatever the closure captures is copied. After the copy, the two isolates have independent objects.
- If the background code appends to a captured list, the caller's list does not change.
- If the caller changes a captured variable after the copy was made, the background code does not see the change.
To get data back, return it from the closure. Isolate.run delivers the return value as the result of the Future. That return value must itself be sendable, and the same rules apply as for captured values.
Large captures cost time
Suppose a screen holds a 50 MB list and you write Isolate.run(() => process(bigList)). Dart must copy the list into the new isolate before process starts. The copy runs on the calling isolate, so a large enough copy can itself cause dropped frames, which is the problem you were trying to avoid.
Ways to reduce this cost:
- Send less. Slice the data to the part the worker needs, or send a file path and let the worker read the file itself.
- Do the loading inside the isolate. Pass a small argument (an ID or path) and fetch or decode the data there. Only the result comes back.
- Use
TransferableTypedDatafor large byte buffers, as covered in the chapter on moving large data.
Flutter: State objects and BuildContext
Flutter makes accidental capture easy. A State object refers to its Widget, to the BuildContext (the element tree), and to many other framework objects. Many of these cannot be sent. A closure written inside a State method that uses any State field or method captures the whole State.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
int sumList(List<int> values) => values.fold(0, (a, b) => a + b);
class TotalView extends StatefulWidget {
const TotalView({super.key, required this.values});
final List<int> values;
@override
State<TotalView> createState() => _TotalViewState();
}
class _TotalViewState extends State<TotalView> {
int? _total;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
// Read what the worker needs before the call.
final data = widget.values;
// Pass a top-level function and its argument; no closure over `this`.
final total = await compute(sumList, data);
if (!mounted) return;
setState(() => _total = total);
}
@override
Widget build(BuildContext context) {
return Text(_total == null ? 'Working...' : 'Total: $_total');
}
}compute(sumList, data) takes a function and one argument instead of a closure, so there is no closure context to over-capture. Everything after the await runs back on the main isolate. That is why setState and mounted are safe there.
A quick checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about an unsendable object when starting the isolate | The closure captured `this`, a port, a socket, or a `BuildContext` | Copy needed values into locals, or use a top-level function |
| Works, but the UI stutters when the job starts | A large object graph is being copied | Send less data, load inside the isolate, or use `TransferableTypedData` |
| Changes made in the isolate are missing in the caller | The captured object was a copy | Return the result from the closure |
| Error appears only after adding a field to a class | The new field holds an unsendable object and `this` is captured | Stop capturing `this` |
Before you write an isolate closure, ask what it can reach. List the variables it names, then follow each one to the objects it refers to. If this or any State is on the list, restructure the code before you run it.
Exercise
This method is meant to parse JSON off the main isolate, but it throws when _controller is a StreamController field and the closure fails to send. Why does it fail, and how do you fix it?
class Feed {
final StreamController<String> controller = StreamController();
String raw = '[]';
Future<List<dynamic>> parse() =>
Isolate.run(() => jsonDecode(_raw) as List<dynamic>);
}
Show answer
The closure reads _raw, which is this._raw, so it captures this. Through this it can reach _controller, which cannot be sent to another isolate. The fix is to copy the field into a local before the call: final raw = _raw; return Isolate.run(() => jsonDecode(raw) as List<dynamic>);. The closure then captures only the string raw, which is sendable.
Exercise
A screen calls Isolate.run(() => analyze(images)), where images is a local list holding 200 MB of decoded pixel data. No error occurs, but the UI freezes for a moment each time the job starts. What is the most likely cause, and name two ways to reduce it.
Show answer
The closure captures images, and Dart copies the whole 200 MB graph into the new isolate before the work starts. That copy runs on the calling isolate and blocks it. To reduce the cost, pass only what the worker needs (for example file paths, so the worker loads and decodes the images itself), or put the bytes in TransferableTypedData so the buffers are handed over without the usual copy.