Sub topic 3
Offloading a Task with `Isolate.run`
This chapter assumes basic Dart syntax, async/await, Future, and a basic understanding of streams. You should also know why Flutter code must keep its UI work responsive.
Why use `Isolate.run`?
Dart runs synchronous code on the current isolate. In a Flutter app, that isolate usually handles both application code and UI work. If a function spends a long time decoding JSON, sorting data, or calculating a result, the event loop cannot process frames or input events during that time. The app may appear frozen, and animations can drop frames.
Isolate.run moves one computation to a new, short-lived isolate. It returns a Future for the computation's result:
Future<T> result = Isolate.run(() {
// Work performed in another isolate.
return someValue;
});The calling isolate continues handling other events while the computation runs. When the work finishes, the result is sent back and the new isolate ends.
Parse JSON outside the calling isolate
The closure passed to Isolate.run contains the work to move. This example decodes a JSON array and converts it to a list of records:
import 'dart:convert';
import 'dart:isolate';
Future<List<Map<String, dynamic>>> parseRecords(String raw) {
return Isolate.run(() {
final decoded = jsonDecode(raw) as List<dynamic>;
return [
for (final entry in decoded) entry as Map<String, dynamic>,
];
});
}
Future<void> main() async {
const raw = '''
[
{"name": "Ada", "score": 98},
{"name": "Lin", "score": 91}
]
''';
final records = await parseRecords(raw);
print(records);
}parseRecords returns immediately with a Future. The await later pauses this asynchronous function, not the whole isolate. The event loop can process other work while the JSON is being decoded.
The value returned by the closure must be transferable between isolates. Simple values such as numbers, strings, booleans, lists, maps, and many typed data objects can be sent. The receiving isolate gets its own representation. It does not receive a reference to mutable state in the original isolate.
Capture only what the task needs
A closure can capture variables from the surrounding scope. Capture makes those values available in the new isolate, but it can also send more data than expected. An instance method may capture this, which can include unrelated fields and objects.
Copy the needed field into a local variable before creating the closure:
import 'dart:isolate';
int sumList(List<int> values) {
return values.fold(0, (total, value) => total + value);
}
class Report {
Report(this.values, this.title);
final List<int> values;
final String title;
Future<int> total() {
final data = values;
return Isolate.run(() => sumList(data));
}
}Here, data identifies the list required by the computation. The closure does not need the report title or the entire Report object.
Results and errors
The result type of Isolate.run is inferred from the closure. If the closure throws, the returned Future completes with an error. Handle it with ordinary try and catch:
import 'dart:isolate';
Future<void> main() async {
try {
await Isolate.run(() {
throw const FormatException('Invalid record data');
});
} on FormatException catch (error) {
print('Parsing failed: ${error.message}');
}
}Use Isolate.run when a computation is independent, takes noticeable time, and can work with transferable input and output. Keep ordinary UI updates, object mutation, and platform-specific work in the calling isolate unless the relevant API explicitly supports background isolates.
Exercise
What does the caller receive immediately from Isolate.run, and what happens if the closure throws?
Show answer
The caller receives a Future. The Future completes with the closure's returned value, or completes with the thrown error.