Sub topic 6
Avoiding Accidental Captures in Closures
This chapter assumes basic Dart syntax, async and await, Future, and basic isolate use. You should also understand that isolates communicate by messages instead of sharing mutable memory.
When you pass a closure to Isolate.run, Dart must send the closure and the values it captures to another isolate. A closure is a function that remembers variables from the surrounding scope. Captured values are part of the work request, even when you did not intend to send them.
How instance members cause accidental captures
Consider this class:
import 'dart:isolate';
int sumList(List<int> values) {
return values.fold(0, (sum, value) => sum + value);
}
class Report {
Report(this.values, this.title);
final List<int> values;
final String title;
Future<int> totalBad() {
return Isolate.run(() => sumList(values));
}
Future<int> totalGood() {
final data = values;
return Isolate.run(() => sumList(data));
}
}The totalBad closure refers to values, which is an instance member. Dart therefore captures this, the Report object, so it can find values later. Sending this may also send title and every other object referenced by the report.
The totalGood method first copies the needed field into a local variable. Its closure captures data, not the whole Report instance. This makes the data flow clearer and reduces the chance of sending unrelated state.
What a closure should capture
Prefer a top-level function for the computation and pass only its input. Top-level functions do not capture an enclosing object.
A closure can safely capture small, sendable values such as numbers, strings, booleans, lists, maps, and records containing sendable values. The exact object graph matters. A list that contains a socket or a plugin handle is not equivalent to a list of integers.
Avoid capturing objects that represent live resources or application state, including:
BuildContext, widgets, and element objectsTextEditingControlleror animation controllers- database connections, sockets, and file handles
ReceivePortandSendPortobjects unless you deliberately use them for communication- plugin instances or platform handles
- services that contain locks, native resources, or other unsendable state
Capture only a snapshot of the values needed by the worker. For example, extract a string or an immutable configuration record before starting the isolate.
Check the boundary before optimizing
The isolate boundary is also a design boundary. Put input preparation on the calling isolate, run pure computation in the worker, and return a small result. Do not make the worker depend on UI objects or services from the caller.
A useful review question is: “If I serialized the values used by this closure, would I send only the job input?” If the answer is no, introduce local variables or move the computation into a top-level function.
Capturing less can also reduce transfer cost. Large object graphs take time and memory to copy. For very large byte buffers, use TransferableTypedData instead of an ordinary captured list when its transfer semantics fit the task.
Exercise
In Isolate.run(() => repository.parse(rawText)), what might the closure capture, and how can you reduce that capture?
Show answer
It can capture this, which includes the repository and its referenced state. Copy rawText to a local variable and call a top-level function such as parse(rawText) inside the isolate.