Summary - Isolates
- Dart course
- Advanced
- Lesson 6/83
- 5 min
Combine spawn, SendPort and compute to write a parallel computation.
Summary - Isolates
This group covered isolates: isolated workers with their own memory and event loop. Unlike threads, they do not share memory; communication happens via SendPort/ReceivePort.
We saw three core APIs: Isolate.spawn (long-lived, message-based), Isolate.run (single result, Dart 3), compute (Flutter wrapper, single result).
Summary: moving CPU-heavy work to the background keeps the UI smooth; for small work the cost is too high.
Practice Summary: single-result compute
Define int faktoriyel(int n) that returns n! (n=5 → 120). Make main async; add var result = await Isolate.run(() => faktoriyel(5)); and print(result);.
Starter code
import 'dart:isolate';
void main() {
// define faktoriyel function (outside main)
// make async; add Isolate.run call with faktoriyel(5)
}Sample solution
import 'dart:isolate';
int faktoriyel(int n) {
var f = 1;
for (var i = 2; i <= n; i++) {
f *= i;
}
return f;
}
void main() async {
var result = await Isolate.run(() => faktoriyel(5));
print(result);
}Expected output
120
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one for ongoing communication?
- compute
- Isolate.spawn Correct answer
- Isolate.run
- Future.wait
Explanation: Isolate.spawn with open ports enables ongoing communication.
2 Match APIs to their uses
| Term | Meaning |
|---|---|
Isolate.spawn |
Long-lived isolate |
Isolate.run |
Single result (Dart 3) |
compute |
Flutter wrapper |
ReceivePort |
Message stream |
3 Communication channel
var port = ____();
var port = ReceivePort();
Explanation: ReceivePort is opened, its sendPort goes to spawn.