Sub topic 11
Transferring large data with TransferableTypedData
This chapter assumes you can already use Isolate.run and Isolate.spawn, and that you know a message sent between isolates is copied. Here you will see when that copy becomes a cost, and how TransferableTypedData reduces it for byte buffers.
The cost of copying messages
Isolates do not share a heap. When you send a message through a SendPort, or capture a value in an Isolate.run closure, the VM copies the object graph into the receiving isolate's heap. For small messages the copy is negligible. For a 50 MB camera frame, a downloaded file, or a decoded audio buffer, it has two costs:
- The sending isolate spends time walking and copying the data. If the sender is the UI isolate, this work can drop frames.
- Memory use briefly doubles, because both isolates hold a copy.
Large byte buffers are a common case where this matters. Images, archives, encrypted payloads, and network responses are usually Uint8List values, and their contents are plain bytes with no object structure to preserve.
TransferableTypedData is a wrapper designed for this case. It moves the bytes out of the Dart heap into an external buffer. Sending that wrapper hands the buffer to the other isolate without another copy of the contents.
How it works
You create the wrapper with TransferableTypedData.fromList, which takes a list of typed data objects. The call does the following:
- It copies the bytes of every list element, concatenated in order, into a native buffer outside the Dart heap. This is the one copy you pay for.
- It returns a small
TransferableTypedDataobject that owns that buffer.
You then send the small object like any other message. The receiver calls materialize(), which returns a ByteBuffer backed by the transferred data. From the buffer you take a view such as asUint8List().
Notice that the transfer is not free. fromList is still O(n) in the size of the data. The benefit is that the copy happens once, in a plain memory copy of bytes, and no second copy is made when the message crosses the isolate boundary.
A complete example
This function counts the non-zero bytes in a buffer on a worker isolate:
import 'dart:isolate';
import 'dart:typed_data';
Future<int> countNonZero(Uint8List bytes) {
final transferable = TransferableTypedData.fromList([bytes]);
return Isolate.run(() {
final data = transferable.materialize().asUint8List();
var count = 0;
for (final b in data) {
if (b != 0) count++;
}
return count;
});
}Points to notice:
- The closure captures only
transferable. It does not capturebytes, so the original list is not copied to the worker. fromListcopies, so the caller'sbytesstays valid and unchanged. You can keep using it.- Materializing happens inside the closure, so it runs on the worker isolate.
- The return value is a small
int, so nothing large travels back.
To run it, call it from a main function:
Future<void> main() async {
final bytes = Uint8List(10 * 1024 * 1024);
for (var i = 0; i < bytes.length; i += 3) {
bytes[i] = 1;
}
print(await countNonZero(bytes));
}This prints 3495253, the number of indexes divisible by 3 below 10,485,760.
Rules for materialize
materialize() has strict rules, and breaking them is the main source of errors with this class.
| Situation | What happens |
|---|---|
| Call `materialize()` once | Returns a `ByteBuffer` that owns the data |
| Call `materialize()` a second time on the same object | Throws an `ArgumentError`, because the data has already been taken |
| Never call `materialize()` | No error. The external buffer is released when the wrapper is garbage collected |
| Send the same wrapper to two isolates | Only one receiver can end up with the data. Create one wrapper per recipient |
| Modify the original `Uint8List` after `fromList` | The wrapper is unaffected, because it holds its own copy |
Treat a TransferableTypedData as a one-shot envelope. Create it, send it, and materialize it exactly once, on the receiving side.
Combining several buffers
fromList accepts a list, and it concatenates the elements. This is useful when you have received data in chunks, for example from an HTTP response stream, and want to hand the whole thing to a worker:
import 'dart:isolate';
import 'dart:typed_data';
Future<int> totalLength(List<Uint8List> chunks) {
final transferable = TransferableTypedData.fromList(chunks);
return Isolate.run(() {
final all = transferable.materialize().asUint8List();
return all.length;
});
}The result is a single contiguous buffer. You avoid first building one large Uint8List with BytesBuilder, which would add another copy on the sending side.
Returning large results
Data often has to come back as well. A worker that decodes, resizes, or encrypts a buffer produces another large buffer. You have two options.
With Isolate.run, the result is returned by exiting the isolate, and the VM can hand the result object to the caller without copying it. Returning a Uint8List directly from an Isolate.run closure is therefore already cheap. You can wrap the result in TransferableTypedData for symmetry, but it is not required.
With a long-lived worker that stays running, results travel through SendPort.send, which copies. In that case, wrapping the result is worthwhile:
import 'dart:isolate';
import 'dart:typed_data';
void invertWorker(SendPort toMain) {
final commands = ReceivePort();
toMain.send(commands.sendPort);
commands.listen((message) {
if (message == null) {
commands.close();
return;
}
final (id, input) = message as (int, TransferableTypedData);
final data = input.materialize().asUint8List();
for (var i = 0; i < data.length; i++) {
data[i] = 255 - data[i];
}
toMain.send((id, TransferableTypedData.fromList([data])));
});
}
Future<void> main() async {
final fromWorker = ReceivePort();
await Isolate.spawn(invertWorker, fromWorker.sendPort);
final events = StreamIterator<dynamic>(fromWorker);
await events.moveNext();
final toWorker = events.current as SendPort;
final source = Uint8List.fromList([0, 1, 2, 255]);
toWorker.send((1, TransferableTypedData.fromList([source])));
await events.moveNext();
final (id, output) = events.current as (int, TransferableTypedData);
print('job $id -> ${output.materialize().asUint8List()}');
toWorker.send(null);
fromWorker.close();
}The output is job 1 -> [255, 254, 253, 0]. Each request carries a job id and a wrapper in a record, as in the worker pattern from the previous chapter. Each side materializes exactly once.
Note that the worker modifies the materialized buffer in place. That is safe because the worker owns that memory after materialize(). The buffer is no longer shared with anyone else.
When it is worth using
A plain Uint8List message is simpler. Use TransferableTypedData when measurements justify it.
- Use it for buffers of roughly hundreds of kilobytes and up that you send repeatedly through ports, such as frames, audio chunks, or file contents.
- Skip it for small buffers. The wrapper adds an object, a native allocation, and the materialize step, which can cost more than a short copy.
- Skip it when the data is not bytes. The class only accepts typed data. A
List<Map>or a custom object still has to be copied normally. - Skip it for a one-off
Isolate.runwhose closure takes data you already hold, if the copy is small compared with the work being done.
Measure with a Stopwatch on a real device in profile mode, not in debug mode, which distorts timing. The main-isolate time spent in the send call is the number to watch, since that is the time that can cause jank.
Platform limits
TransferableTypedData is part of dart:isolate and works on native platforms: Android, iOS, desktop, and the Dart VM. Dart on the web does not run dart:isolate isolates, so on the web you would use web workers and their own transfer mechanisms instead. Flutter's compute falls back to running on the main thread on the web, which means no data is transferred at all.
Common mistakes
- Materializing twice. The second call throws
ArgumentError. Store theUint8Listview from the first call if you need it again. - Capturing the original list as well. If the closure references
bytesas well astransferable, the VM copiesbytesto the new isolate and you lose the benefit. - Expecting zero cost.
fromListstill copies once. The saving is in avoiding the second copy and the work on the sending isolate during the send. - Sending one wrapper to several workers. Only one can receive the data. Build one wrapper per recipient.
- Wrapping tiny buffers. The overhead is larger than the gain.
Exercise
A function calls TransferableTypedData.fromList([bytes]), sends the result to a worker, and then on the main isolate reads bytes[0]. Is this safe, and why? What happens if the worker calls materialize() twice?
Show answer
Reading bytes[0] is safe, because fromList copies the contents into its own external buffer and leaves the original Uint8List untouched. The worker's second materialize() call throws an ArgumentError, because the first call already took ownership of the data. The worker should keep the Uint8List view from the first call.
Exercise
You write Isolate.run(() => process(bytes)) and also create final t = TransferableTypedData.fromList([bytes]) before it, but the closure still refers to bytes and never uses t. Does this avoid copying bytes to the worker? What change fixes it?
Show answer
No. The closure captures bytes, so the VM copies it to the new isolate, and t only added an extra copy. Fix it by having the closure capture only t and call t.materialize().asUint8List() inside the closure, then pass that view to process.