Flutter's `compute`: Offload Heavy Work from the UI Thread
Flutter's `compute` function runs heavy calculations in the background to prevent your app's UI from freezing. Use it for tasks like parsing large JSON or complex math. The footgun: on the web, it runs on the same event loop, not in a true parallel thread.
WHY IT EXISTS Flutter needs to render frames consistently to feel smooth. Any calculation on the main thread that takes more than a few milliseconds can block rendering, causing stuttering or "jank." The compute function provides a simple way to move this work into the background, keeping the UI responsive.
THE MENTAL MODEL Think of compute as hiring a temporary assistant (an Isolate) for a single, heavy task. You give them instructions (the callback function) and the necessary materials (the message). While they work, you're free to keep the main business running smoothly (the UI). When they're done, they hand you back the result.
HOW IT WORKS The compute function takes a top-level or static function and a single argument for it. On native platforms (iOS, Android), it spawns a new Isolate—an independent worker with its own memory—runs the function there, and returns the result as a Future. On the web, which lacks true multi-threading in the same way, it schedules the work on the main event loop, providing asynchrony but not parallelism.
WHEN TO USE IT Use compute for self-contained, CPU-intensive operations that take longer than a few milliseconds. This is perfect for parsing large JSON documents, applying complex filters to an image, or running heavy mathematical algorithms. It's a direct way to prevent these tasks from dropping UI frames.
WHEN NOT TO USE IT Avoid compute for very short tasks (under a millisecond), as the overhead of spawning an isolate is not worth it; use SchedulerBinding.scheduleTask instead. It's also unnecessary for I/O-bound work like standard network requests, as Dart's async/await already handles that without blocking the UI.
ONE CANONICAL EXAMPLE To check if a large number is prime without freezing the app, you can offload the work. First, define a top-level function: bool isPrime(int n) { /* heavy loop logic */ }. Then, from your UI event handler, you call it with compute: final bool result = await compute(isPrime, 999999937);. The UI remains interactive while the calculation happens in the background.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.