compute
- Dart course
- Advanced
- Lesson 4/83
- 5 min
Learn simple isolates with compute.
The compute function
compute is Flutter's simple isolate helper. It runs a single function on a background isolate and returns the result to the main isolate.
Signature: Future<R> compute<Q, R>(FutureOr<R> Function(Q) callback, Q message). callback must be top-level or static; message is its single parameter.
It hides the manual spawn + SendPort ceremony. Ideal for heavy single-result work: file parsing, image processing, large JSON.
compute vs Isolate.spawn
compute is a thin wrapper over Isolate.spawn. It makes one-shot work easy: give a function, get a result.
Isolate.spawn suits long-lived isolates: message channels stay open, multiple messages are exchanged.
Choose: single result → compute; ongoing conversation → Isolate.spawn + SendPort.
Practice Compute a square with compute
Define a top-level int kareAl(int x) => x * x; function. Make main async; add var result = await compute(kareAl, 7); and print(result);.
Starter code
import 'package:flutter/foundation.dart';
void main() {
// define kareAl function (outside main)
// make async; add compute call with kareAl(7)
}Sample solution
import 'package:flutter/foundation.dart';
int kareAl(int x) => x * x;
void main() async {
var result = await compute(kareAl, 7);
print(result);
}Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When should you use compute?
- When a continuous stream is needed
- To share memory
- To speed up UI drawing
- For heavy single-result work Correct answer
Explanation: compute is ideal for heavy single-result work.
2 Match the compute parts
| Term | Meaning |
|---|---|
compute |
Background helper |
callback |
Function to run |
message |
Single input parameter |
Future<R> |
Return type |
3 compute call
var result = await ____(kareAl, 7);
var result = await compute(kareAl, 7);
Explanation: compute runs kareAl(7) in the background.