While your app grows bigger, you might not be surprised that it starts to run slower. The situation happens with some new features, related to heavy tasks such as decoding images with high resolution, computing complicated math, or reading large files. All of these result in one annoying thing — Jank.
This session in Google I/O 2022 reveals the mechanism of how Flutter keeps the app smooth with 60 fps, why it slows down, and how we can fix it.
Table Of Content
- Isolate and event loop
- Core libraries/system APIs
- Spawn an Isolate
- Compute Isolate — short-lived background tasks
- Worker Isolate — Long-lived background tasks - Recap
- References
Isolate and event loop
All the dart code runs in an isolate with an event loop. Each isolate has a single thread running an event loop, with a chunk of private memory. It is kinda like process
in Android. The event loop contains two queues: microtask queue
and event queue
. We won’t go into the microtask queue here, if you’re interested, please refer to this post.
The event loop continuously consumes the events. Repaint
is the most frequently added event. In order to reach 60 fps, Flutter Engine repaints the UI every 16ms, which means the Repaint
event is added 60 times per second. You can do other tasks between the Repaint
events, however, it might cause jank if the task spends too much time. How can we prevent that from happening? Here are 2 ways to achieve it:
- Let core libraries / system APIs handle it.
- Spawn a new isolate to handle it.