Flutter · One codebase, native feel
When and how do you use isolates?
Short answer
Use an isolate for CPU-heavy work that would block the UI isolate. Isolates have separate memory and communicate by messages, so data must be copied or transferred.
Every Dart thread is an isolate with its own event loop and heap. There is no shared mutable memory, which removes data races but means you cannot pass arbitrary object graphs by reference. Small immutable messages are copied; large buffers can be transferred to avoid the copy cost.
Future<int> countPrimes(int limit) {
return Isolate.run(() {
var count = 0;
for (var n = 2; n <= limit; n++) {
var prime = true;
for (var d = 2; d * d <= n; d++) {
if (n % d == 0) {
prime = false;
break;
}
}
if (prime) count++;
}
return count;
});
}- Use Isolate.run or compute for one-off CPU tasks
- Use long-lived isolates with ports for repeated work such as audio or database processing
- Send simple values or typed data; closures and native handles usually cannot cross
- Move large buffers with TransferableTypedData to avoid copying
- Background isolates need explicit setup to use platform channels
Costs and constraints
Spawning an isolate costs memory and startup time, so it is not worth it for trivial work. Sending large JSON structures between isolates adds serialisation overhead. On the web, isolates map to workers with different capabilities, so code that depends on dart:io must be isolated behind conditional imports.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What data can be sent between isolates?
- 2How does TransferableTypedData reduce copying?
- 3How would a background isolate use a plugin channel?
- 4Why is spawning an isolate per API call usually wrong?
Say it in the interview
I reach for an isolate when CPU-bound work would block frames, such as large parsing, image processing or heavy computation. Isolates do not share memory, so I pass messages and return a result. Isolate.run is fine for one-off tasks, while long-lived workers make sense for repeated work. I avoid spawning them for I/O or trivial jobs because startup and message copying have real cost.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Flutter mock interview and get scored feedback on depth, clarity and confidence.