Sub topic 4
Using compute in Flutter
This chapter assumes you know async/await and Future, and that you know why Flutter's UI isolate must stay responsive. It also assumes you have read the previous chapter on Isolate.run. Here you will learn how compute fits on top of that, how to use it in widgets, and where it differs from calling Isolate.run yourself.
What compute is
compute is a function in package:flutter/foundation.dart. It runs a callback with one argument in a separate isolate and returns a Future of the result.
Future<R> compute<M, R>(
ComputeCallback<M, R> callback,
M message, {
String? debugLabel,
})M is the type of the single argument and R is the type of the result. ComputeCallback<M, R> is a typedef for FutureOr<R> Function(M message). The callback may be synchronous or return a Future.
On native platforms (Android, iOS, desktop), current Flutter versions implement compute on top of Isolate.run. The call does roughly this:
- It starts a short-lived isolate.
- It runs
callback(message)there. - It sends the result back and shuts the isolate down.
On the web, there are no isolates in the dart:isolate sense. compute still compiles and runs, but the callback executes on the same thread, so it does not parallelize anything. The last section of this chapter returns to this.
A first example
The classic demonstration is a deliberately slow function. A naive recursive Fibonacci takes long enough at n = 35 to drop frames on most devices.
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;
}The callback fib is a top-level function. It takes one int and returns an int, so compute infers M = int and R = int. While fib runs in the worker, the UI isolate keeps handling input and drawing frames, and the await simply suspends computeFib.
The callback rules
The callback is the part of compute where mistakes happen most often.
- Prefer a top-level function or a static method. The Flutter documentation asks for this. With a plain function, nothing but the function and the message crosses the isolate boundary.
- A closure also compiles on native platforms, because
Isolate.runaccepts closures. A closure carries everything it captures, which is the problem covered in the pitfalls section below. - The callback takes exactly one argument. To pass several values, bundle them (see the next section).
- The callback sees fresh global state. Each isolate has its own copy of top-level variables and static fields. If you set a global in the UI isolate and read it inside the callback, you get the initial value, not what you set.
Passing more than one value
Because compute accepts a single message, use a Dart 3 record or a small class to carry several values.
import 'package:flutter/foundation.dart';
int countAbove((List<int>, int) args) {
final (values, threshold) = args;
return values.where((v) => v > threshold).length;
}
Future<int> runCount() {
return compute(countAbove, ([1, 5, 9, 12], 4));
}Records of sendable values are themselves sendable. The List<int> is copied into the worker, which is fine here. For large lists, copying costs time, so the choice of what to pass matters. The next chapter covers what can be sent and what gets copied.
Using compute in a widget
The most common use is parsing a large payload so that building the list does not freeze the screen. The following app is complete and runnable. It generates and parses 50,000 records in the worker and shows a spinner meanwhile.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Item {
const Item(this.id, this.name);
final int id;
final String name;
}
// Top-level so that only the function and an int cross the boundary.
List<Item> buildAndParse(int count) {
final raw = jsonEncode([
for (var i = 0; i < count; i++) {'id': i, 'name': 'item $i'},
]);
final decoded = jsonDecode(raw) as List<dynamic>;
return [
for (final e in decoded.cast<Map<String, dynamic>>())
Item(e['id'] as int, e['name'] as String),
];
}
void main() => runApp(const MaterialApp(home: ItemsPage()));
class ItemsPage extends StatefulWidget {
const ItemsPage({super.key});
@override
State<ItemsPage> createState() => _ItemsPageState();
}
class _ItemsPageState extends State<ItemsPage> {
late final Future<List<Item>> _items =
compute(buildAndParse, 50000, debugLabel: 'buildAndParse');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('compute demo')),
body: FutureBuilder<List<Item>>(
future: _items,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Failed: ${snapshot.error}'));
}
final items = snapshot.data;
if (items == null) {
return const Center(child: CircularProgressIndicator());
}
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, i) => ListTile(title: Text(items[i].name)),
);
},
),
);
}
}Three details in this example matter:
- The
Futureis stored in alate finalfield. If you calledcomputeinsidebuild, every rebuild would start a new isolate and a new job. - The spinner animates smoothly during parsing. That is the observable proof that the UI isolate is free. If you replace
compute(buildAndParse, 50000)with a direct call, the spinner freezes, or never appears at all because the work blocks before the first frame. debugLabelnames the work in profiling tools such as DevTools. It has no effect on behavior.
The result, a List<Item> with 50,000 plain objects, is sendable because Item holds only numbers and strings. In current Flutter versions, Isolate.run returns its result with Isolate.exit, which transfers the object graph to the caller without copying it. The argument is the opposite: it is copied into the new isolate.
Errors
If the callback throws, the Future returned by compute completes with that error, so ordinary try/catch and FutureBuilder.hasError work.
import 'package:flutter/foundation.dart';
int parseAge(String text) {
final age = int.parse(text); // throws FormatException on bad input
if (age < 0) throw RangeError.value(age, 'age');
return age;
}
Future<void> demo() async {
try {
final age = await compute(parseAge, 'abc');
debugPrint('age = $age');
} on FormatException catch (e) {
debugPrint('Bad input: ${e.message}');
}
}The error object is sent back to the caller, so it must itself be sendable. Standard exceptions such as FormatException and RangeError are fine. An error object that holds unsendable fields, such as a native handle, cannot cross the boundary cleanly. Keep your own exception classes plain.
compute compared with the alternatives
| Aspect | `compute` | `Isolate.run` | `Isolate.spawn` with ports |
|---|---|---|---|
| Import | `package:flutter/foundation.dart` | `dart:isolate` | `dart:isolate` |
| Lifetime | One job, then exits | One job, then exits | You decide |
| Arguments | Exactly one | A closure, any captures | Messages through ports |
| Works on the web | Yes, but without parallelism | No, `dart:isolate` is unavailable | No |
| Best for | Flutter app code that targets several platforms | Native-only or pure Dart code | Many jobs, streaming results, state kept in the worker |
On native-only projects, Isolate.run is usually the more flexible choice, because you write a closure and are not limited to one argument. Use compute when your code also builds for the web, or when you prefer one cross-platform call.
Pitfalls
Other problems you are likely to meet:
- Starting a job per rebuild or per keystroke. Each call creates an isolate, which has a startup cost. Cache the
Future, or debounce the input. - Wrapping tiny jobs. If the work takes under a frame (about 16 ms at 60 fps), the spawn and copy overhead can exceed the savings. Measure in profile mode before moving work off the UI isolate.
- Expecting plugins to work. The worker isolate does not automatically have access to platform channels. Calling a plugin from
computecan fail with a missing-binding error. A later chapter in this tutorial covers how to initialize a background isolate for plugins. - Mutating shared state. The worker cannot change objects in the UI isolate. It can only return a result. Update your state after the
await. - Widget tests.
testWidgetsruns inside a fake-async zone, so a real isolate may never complete. Wrap that part of the test intester.runAsync.
The web
Flutter on the web compiles to JavaScript or WebAssembly. There, compute runs the callback on the same thread. Your code stays portable and the result is delivered asynchronously, but a heavy callback still blocks the UI. On the web, real parallelism needs a different mechanism, such as web workers, which is outside this chapter. Plan for the web case by keeping heavy work small, doing it on a server, or splitting it into chunks that yield between pieces.
Exercise
A teammate writes compute(heavy, data) inside build() of a StatelessWidget, and the app starts using a lot of CPU whenever the user scrolls. What is the likely cause, and how would you fix it?
Show answer
build() runs many times, for example on every rebuild triggered by scrolling or animation, so each run starts a new isolate and repeats the heavy job. Start the job once, for example in initState of a StatefulWidget or in a state-management layer, store the returned Future in a field, and give that field to FutureBuilder. Also confirm that heavy is a top-level function.
Exercise
You need to call compute with a function that needs a List<int> and a String prefix. compute accepts one argument. How do you pass both, and what type does the callback take?
Show answer
Bundle them in a record, for example compute(process, (values, 'id-')). The callback is declared as R process((List<int>, String) args) and unpacks the record with final (values, prefix) = args;. A small class with two final fields also works, as long as its fields are sendable.
Exercise
On a native device, compute(fib, 35) keeps the UI smooth, but the same call in a Flutter web build causes the page to stutter. Why?
Show answer
On the web, compute does not create a real isolate. It runs the callback on the same thread as the UI, asynchronously, so a CPU-heavy callback still blocks rendering. The API is portable, but the parallelism is native-only.