Sub topic 12
Moving Heavy Work to Isolates
This chapter assumes that you can write Flutter widgets, use async and await, and run commands with the flutter tool. It also assumes that you understand that Flutter normally builds widgets and handles input on one UI isolate.
Why heavy work causes startup and frame problems
An isolate is an independent Dart execution context with its own memory and event loop. Flutter's UI isolate handles widget builds, input, animations, and painting. If that isolate spends too long parsing a large response, decoding data, or calculating results, it cannot render the next frame.
The result is a janky interface or a delayed first screen. Making a function async does not fix CPU-heavy work. An async function can still occupy the UI isolate while it calculates. await helps with waiting for input and timers, not with computation that keeps the CPU busy.
Move work to another isolate when the work is CPU-bound and takes long enough to affect interaction. Typical examples include:
- Parsing large JSON or CSV documents.
- Compressing or encrypting data.
- Resizing or processing many images.
- Sorting or transforming a large collection.
- Running a search over a large local data set.
The `Isolate.run` working model
Isolate.run starts a computation on another isolate and returns a Future for its result. Dart transfers the input and output between isolates. Isolates do not share ordinary mutable objects, so the worker cannot directly update a widget or a field owned by the UI isolate.
Keep the worker function independent from Flutter widgets and BuildContext. Pass simple, transferable data such as strings, numbers, lists, and maps. Return a result, then update the UI after the future completes.
import 'dart:io';
import 'dart:isolate';
List<int> parseNumbers(String raw) {
return raw
.split(',')
.map((part) => int.parse(part.trim()))
.toList();
}
Future<void> main() async {
final raw = await File('numbers.csv').readAsString();
final numbers = await Isolate.run(() => parseNumbers(raw));
print('Parsed ${numbers.length} numbers');
}In a Flutter app, call the function from an event handler or a state-management method. While the future is pending, show a loading state. Check that the widget or controller is still usable before applying the result if the operation can outlive the screen.
Common errors and trade-offs
An isolate has startup and message-transfer costs. Moving a tiny calculation to another isolate can be slower than doing it directly. Measure the real operation before adding an isolate.
The worker must return values that Dart can transfer. Do not pass a BuildContext, an open socket, a controller, or a widget. Open resources inside the worker when appropriate, or pass the data needed to create them.
Exceptions from the worker complete the returned future with an error. Handle that future like any other asynchronous operation:
try {
final result = await Isolate.run(() => parseNumbers(raw));
// Update application state with result.
} on FormatException catch (error) {
// Show an invalid-input message.
print('Could not parse input: $error');
}Use Isolate.run for one substantial operation. For repeated jobs, a long-lived isolate with ReceivePort and SendPort can avoid repeated startup costs, but it requires lifecycle management and a message protocol.
> callout tip > Do not use an isolate as a replacement for asynchronous I/O. Network and file operations already yield while waiting. Use an isolate when the data processing after the I/O is the expensive part.
Exercise
Exercise
Why might marking a large JSON parser as async fail to prevent dropped frames, and what change would help?
Show answer
Async syntax does not move CPU work off the UI isolate. Run the parser with Isolate.run and await its result before updating the UI.