Google I/O 2022 —When, why, and how to multithread in Flutter

How does jank happen and how to fix it?

Evan Fang

--

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

  1. Isolate and event loop
  2. Core libraries/system APIs
  3. Spawn an Isolate
    - Compute Isolate — short-lived background tasks
    - Worker Isolate — Long-lived background tasks
  4. Recap
  5. 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:

  1. Let core libraries / system APIs handle it.
  2. Spawn a new isolate to handle it.

Core libraries / system APIs

--

--

Evan Fang

An Android/Flutter engineer at LINE Corporation.