Sub topic 1
Why heavy work freezes your app
This chapter explains why slow Dart code makes a Flutter app stutter, how isolates avoid that problem, and how to move one job onto an isolate with Isolate.run.
Prerequisites
You should know Dart syntax, async and await, and Future. You should also know that a Flutter widget tree is redrawn on the UI thread.
Why heavy work freezes your app
Dart runs your code on an event loop. The event loop is a loop that picks up one task at a time, such as a button tap, a timer, or a network reply, and runs it to completion. While one task runs, nothing else in that isolate runs.
Flutter aims to draw 60 frames per second, so each frame has about 16 milliseconds of work. If a function takes 500 milliseconds of pure computation, the app skips about 30 frames. Taps and animations look frozen during that time.
Async code does not fix this by itself. An await only yields when the awaited work is waiting on I/O, such as a file or network call. A loop that crunches numbers never yields.
Isolates: separate heaps, message passing
An isolate is an independent unit of Dart code with its own event loop and its own memory heap. Isolates do not share objects. One isolate cannot read or change a variable inside another.
Isolates communicate by sending messages. A message is copied or transferred to the receiver, so each isolate always owns its own data. This design removes data races, where two threads change the same value at once.
The main isolate runs your UI. Moving heavy work to a second isolate keeps the UI loop free to draw frames.
Offloading a task with Isolate.run
Isolate.run starts an isolate, runs a function there, and returns the result as a Future. The caller does not need to manage ports.
import 'dart:isolate';
int sumTo(int n) {
var total = 0;
for (var i = 1; i <= n; i++) {
total += i;
}
return total;
}
Future<void> main() async {
final result = await Isolate.run(() => sumTo(100000000));
print('Sum: $result');
}The main isolate stays responsive while sumTo runs. The returned value is copied back when the work finishes.
Exercise
If sumTo takes 2 seconds and you call it directly inside a button handler, what does the user see, and how does wrapping the call in Isolate.run change that?
Show answer
The UI freezes for about 2 seconds because the button handler blocks the event loop. With Isolate.run, the computation runs on another isolate, so the UI keeps drawing frames and responds to taps while the result is computed.