Sub topic 4
Using `compute` in Flutter
This chapter assumes basic Dart syntax, async and await, Future, and a basic understanding of why Flutter's UI isolate must stay responsive. You should also know how to run a Flutter application.
Flutter's compute function is a convenient way to run one calculation away from the calling isolate. On native platforms, Flutter starts a separate isolate, passes it one argument, runs a top-level or static function, and returns the result as a Future.
Why use `compute`?
Flutter processes input, layout, painting, and Dart callbacks on the main isolate. A long synchronous calculation blocks that isolate. While it is blocked, frames can be late and taps or timers must wait.
compute is useful for a self-contained operation such as:
- Parsing a large JSON document.
- Sorting or filtering a large collection.
- Performing CPU-heavy mathematics.
- Converting or analyzing binary data.
It is not a replacement for asynchronous I/O. An HTTP request already yields while waiting for the network. compute is for CPU work that would otherwise occupy the main isolate.
A complete example
The callback should be a top-level function or a suitable static function. It receives one message and returns one result.
import 'package:flutter/foundation.dart';
int fib(int n) => n < 2 ? n : fib(n - 1) + fib(n - 2);
Future<int> computeFib() async {
final result = await compute(fib, 35);
return result;
}
Future<void> main() async {
final result = await computeFib();
print('Fibonacci result: $result');
}The call compute(fib, 35) sends 35 to the worker. The worker runs fib(35). Flutter completes the returned Future<int> when the worker sends the integer back.
The main isolate can continue processing frames while the worker calculates. The await pauses only the current asynchronous function. It does not block the isolate.
What crosses the isolate boundary?
Isolates do not share mutable memory. The argument and return value must be transferable between isolates. Simple values such as numbers, strings, booleans, lists, maps, and many typed data values can usually be sent. Flutter copies ordinary transferable objects as needed.
| Good input | Risky input |
|---|---|
| `int`, `String`, and simple lists or maps | Open files, sockets, controllers, and arbitrary plugin objects |
Keep the message small when possible. Sending a huge object can itself cost time and memory, so moving work to another isolate is not automatically faster.
A callback that depends on a BuildContext, widget state, database connection, or platform object cannot safely use those objects inside compute. Extract the plain data needed by the calculation first.
Errors and platform behavior
If the callback throws, the returned future completes with an error. Handle it with ordinary try and catch around await.
On native Flutter platforms, compute uses a separate isolate. On the web, Dart does not provide the same isolate model, so compute runs the callback in the current event loop. Code that depends on parallel execution therefore needs platform-aware expectations.
Use compute when the work is large enough to justify its setup cost and has clear input and output. Keep ordinary small calculations on the calling isolate.
Exercise
Why must a compute callback avoid using a widget's BuildContext?
Show answer
The callback runs in another isolate, which cannot access the widget tree or share the calling isolate's mutable objects.