My 2 cents on Image Processing in Flutter

Daniel Kao
2 min readJul 29, 2019

--

In Flutter, it’s easy to load an Image widget. Flutter provides several different ways: You can use Image.network(), Image.asset() or Image.memory() depending on the source you want to load the image.

However, Flutter is known to be slow at processing image, including decoding image when the source file is relatively large.

The above code snippet is an example of loading an Image from the internet.

At line 8: download the data from the internet;

At line 12: an Image Widget is created;

At line 14: then ask system to build the Widget again by using setState().

This code works, but UI often blinks when the image is replacing the placeholder on screen.

precacheImage() Come to Rescue!

After searching for a long time on the internet, I finally found the way to fix this problem.

Image.memory() is just setting up the Image Widget; it does not mean the Widget is ready to be drawn on screen yet. That’s why you would see the short period of blank screen on the animation above.

To solve this, all you have to do is wait until the Image Widget is ready, and then call setState() afterward. That’s where precacheImage() comes to rescue. It can help you to cache (or load) the Image in advance. When you really need to draw it, you don’t have to spend time decoding the binary again.

At line 14: we added the code, and that’s it!

Look at the no-blink-anymore UI! Hope this tip is useful for you too.

--

--

Daniel Kao
Daniel Kao

Written by Daniel Kao

2023 年新書出版! Android 開源專案「真」實戰啟航:瀏覽器 App EinkBro 開發者帶你逐步從 UI 設計、UX 提升到多功能實現秘技全解析

Responses (1)