Sub topic 1
Why heavy work freezes your app
A Dart app can run a progress spinner, answer taps, and download files at the same time. Yet one long loop can stop all of it. This chapter explains the mechanism behind that freeze. The rest of the tutorial builds on it, because every isolate technique exists to avoid this problem.
Prerequisites
This chapter assumes you have the following:
- Basic Dart syntax, including
async,await, andFuture. - A basic idea of what a
Streamis. - For the Flutter sections, you know what a widget is and why the UI must stay responsive.
You do not need any knowledge of isolates yet. The next chapter introduces them.
One isolate, one thread of execution
Dart code always runs inside an isolate. An isolate is an independent worker with its own memory and its own event loop. Your main function starts in the main isolate, and in a Flutter app this is the isolate that builds widgets, handles taps, and runs your callbacks.
Inside one isolate, only one piece of Dart code runs at a time. Nothing interrupts a function while it runs. Dart uses cooperative scheduling, so the function must finish or reach an await before anything else gets a turn.
The event loop
Each isolate keeps two queues of pending work:
- The microtask queue holds short tasks, such as the continuation of a completed
Future, or a callback passed toscheduleMicrotask. - The event queue holds everything else: timers firing, taps and other input, results from file or network I/O, and messages from other isolates.
The loop runs main, then empties the microtask queue. After that it takes one event, runs its handler to completion, and empties the microtask queue again. It repeats this until the app exits.
The step "run its handler to completion" explains the freeze. While a handler runs, the loop cannot reach any other event. Every queued event waits, including a tap or a request to draw the next frame.
Futures are not threads
A common misunderstanding is that marking a function async moves its work somewhere else. It does not. An async function runs synchronously until it reaches its first await. After that, the rest of the function runs later, on the same isolate, as a microtask or event.
The following program shows this. A timer should tick every 100 ms. The async function then does a CPU-bound loop.
import 'dart:async';
int heavy(int n) {
var s = 0;
for (var i = 0; i < n; i++) {
s += i % 7;
}
return s;
}
Future<int> heavyAsync(int n) async {
// No await before the loop, so this runs synchronously.
return heavy(n);
}
Future<void> main() async {
final clock = Stopwatch()..start();
var last = 0;
final timer = Timer.periodic(const Duration(milliseconds: 100), (_) {
final now = clock.elapsedMilliseconds;
print('tick, ${now - last} ms since the previous tick');
last = now;
});
await Future<void>.delayed(const Duration(milliseconds: 350));
print('starting heavy work');
// Raise or lower n so the loop takes about one second on your machine.
final result = await heavyAsync(1500000000);
print('heavy work finished: $result');
await Future<void>.delayed(const Duration(milliseconds: 250));
timer.cancel();
}Typical output looks like this, though exact numbers differ per machine:
tick, 101 ms since the previous tick
tick, 100 ms since the previous tick
tick, 100 ms since the previous tick
starting heavy work
heavy work finished: 4499999998
tick, 1214 ms since the previous tick
tick, 100 ms since the previous tickThe timer was due about ten times during the loop, but none of those callbacks could run. After the loop ended, one late tick arrived with a gap of over a second. Nothing was wrong with the timer. The loop simply never got control back.
Waiting is cheap, computing is not
If async does not use threads, why does await http.get(...) not freeze the app? The reason is that the operating system does the waiting, not your Dart code. Your isolate hands the request off and returns to the event loop. When the response arrives, the loop receives an event and resumes your code. During the wait, the isolate is free.
The cost appears when Dart code must do work with the data. The table shows common cases.
| Operation | Blocks the event loop? | Why |
|---|---|---|
| `await` on a network request | No, while waiting | The OS waits for the data. |
| `jsonDecode` on a 10 MB string | Yes | Parsing is CPU work in your isolate. |
| `File.readAsString()` | Mostly no, for the read | The read is asynchronous, but decoding a very large result still costs CPU time. |
| `File.readAsStringSync()` | Yes | The call waits for the read to finish. |
| Sorting or filtering a list with a million items | Yes | Pure computation. |
| A recursive function such as Fibonacci of 40 | Yes | Pure computation. |
| Image decoding with `Image.network` | No, in practice | Flutter's engine decodes images on its own threads. |
The distinction to remember is this. A call blocks the loop if your Dart code spends CPU time on it, or if you used a synchronous API that waits. Time spent waiting inside an await is free.
The frame budget
In Flutter, the cost of blocking is easy to see because the screen is redrawn many times per second. The engine asks the main isolate for a new frame at the display's refresh rate. Your code has a fixed time budget per frame to build, lay out, and paint the widget tree.
| Refresh rate | Time per frame |
|---|---|
| 60 Hz | about 16.7 ms |
| 90 Hz | about 11.1 ms |
| 120 Hz | about 8.3 ms |
The budget has to cover your handler and the framework's own work. If one handler runs for 200 ms at 60 Hz, around twelve frames are skipped. The screen then shows the same image for 200 ms. Animations stop, scrolling stutters, and taps feel ignored. This effect is called jank.
Flutter actually uses two threads for drawing. The UI thread runs your Dart code and produces a description of the frame. A separate raster thread turns that description into pixels. Heavy work in your Dart code stalls the UI thread, so the raster thread has nothing new to draw, and the display repeats the old frame.
A Flutter example you can feel
The following app shows an endlessly spinning indicator. The button runs a slow synchronous function. Run it and press the button: the spinner stops while the computation runs.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: JankDemo()));
int fib(int n) => n < 2 ? n : fib(n - 1) + fib(n - 2);
class JankDemo extends StatefulWidget {
const JankDemo({super.key});
@override
State<JankDemo> createState() => _JankDemoState();
}
class _JankDemoState extends State<JankDemo> {
int? _result;
Future<void> _run() async {
// Still synchronous: there is no await before the heavy call.
final value = fib(40);
setState(() => _result = value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 24),
ElevatedButton(onPressed: _run, child: const Text('Compute')),
Text('Result: ${_result ?? "none yet"}'),
],
),
),
);
}
}Even though _run is async, it does not help. The spinner is driven by an animation ticker, and its next tick is an event that cannot run until fib(40) returns. Debug builds are much slower than release builds, so the freeze is longer in debug mode. Always judge performance in profile mode, covered below.
Other things that starve the loop
Long loops are the usual cause, but two more patterns deserve a mention.
- Synchronous I/O APIs, such as
readAsStringSync,writeAsBytesSync, andsleepfromdart:io. They block the isolate for as long as the operation takes. - A microtask that keeps scheduling more microtasks. The loop drains the microtask queue completely before it looks at the event queue, so a chain of microtasks that never ends prevents any event from running, including frames.
Option one: yield control yourself
Before reaching for isolates, you can sometimes keep the work on the main isolate by cutting it into slices. After each slice, you await something so that queued events can run. This code sums numbers in slices of roughly 8 ms:
Future<int> sumChunked(int n) async {
var sum = 0;
final slice = Stopwatch()..start();
for (var i = 1; i <= n; i++) {
sum += i;
// Check the clock only occasionally, because reading it costs time.
if (i % 100000 == 0 && slice.elapsedMilliseconds > 8) {
await Future<void>.delayed(Duration.zero); // let other events run
slice.reset();
}
}
return sum;
}This keeps the UI moving, and it needs no message passing. Its drawbacks are real, though:
- You must restructure the algorithm so it can pause, which is hard for recursive code or code inside a library.
- Total time grows, because the work still shares one thread with everything else.
- It cannot use more than one CPU core.
- The slice length is a guess that you must tune.
Option two: move the work to another isolate
An isolate has its own event loop and runs on its own thread. If the heavy computation runs there, the main isolate stays free to handle taps and draw frames. Isolates do not share memory, so data travels between them as messages. The following chapters cover that model and the APIs for it, starting with Isolate.run.
Measuring before you decide
Do not guess where the time goes. Use these tools:
- Run the app in profile mode with
flutter run --profileon a real device. Debug mode adds overhead that distorts the results. - Open the Performance view in Flutter DevTools. Frames that exceed the budget appear in red, and the timeline shows which function ran during them.
- Wrap a suspect section with
Timeline.timeSyncfromdart:developerto give it a name in the timeline. - For a quick check in plain Dart, use
Stopwatch, as in the first example above.
Common mistakes
- Assuming
asyncorFuturemoves work off the UI. It only changes when the code runs, not where. - Benchmarking in debug mode and concluding that something is slow when it is fast in release.
- Testing with small data. A parse that takes 3 ms on a test file can take 300 ms on a real user's data.
- Using a synchronous file or network API in a handler because it was shorter to write.
Exercise
A function marked async has no await inside it and runs a loop that takes two seconds. Does the UI stay responsive while it runs? Explain why.
Show answer
No. An async function runs synchronously until its first await. With no await, the whole loop runs inside one event handler on the main isolate. The event loop cannot process taps, timers, or frame requests until the handler returns, so the UI freezes for two seconds.
Exercise
A screen refreshes at 120 Hz. Roughly how long can your code spend on one frame, and what visible effect do you see if a button handler runs for 100 ms?
Show answer
About 8.3 ms per frame. A 100 ms handler misses roughly twelve frames, so animations pause, scrolling stutters, and the display shows the same image until the handler finishes.
Exercise
Which of these blocks the event loop of the calling isolate: await http.get(url) while the response is in transit, jsonDecode of a 20 MB string, or File.readAsBytesSync() on a large file?
Show answer
jsonDecode blocks because it is CPU work in your isolate, and readAsBytesSync blocks because the synchronous call waits for the read. The await on the network request does not block while the response is in transit, because the OS does the waiting and the loop stays free.