Tree Shaking in Flutter: Optimize Your App Size and Performance

Syed Ahmed Usman
2 min read6 days ago

--

Tree shaking is a programming technique that removes unused code from the final bundle, making the code more efficient. You can imagine it like shaking a tree, where the dead leaves start falling. It works the same way in Flutter, reducing the size of the application by removing unused assets, dead code, or unnecessary code.

When Tree shaking happens

When you are building your app in release mode, you may see this output in the process:

This is because, in release mode, tree shaking applies automatically when you build your app in release mode using this command

flutter build apk --release

However you can disable tree shaking using this flag with your release command:

flutter build apk --release --no-tree-shake-icons

You can compare the result in below screenshot of build with and without tree-shaking

Flutter ignores tree shaking in debug mode as in debug mode since the target is faster development not optimization.

Why Is Tree-Shaking Important in Flutter?

  • Smaller App Size: Tree-shaking ensures that unused code doesn’t unnecessarily increase the size of the app binary.
  • Faster Load Times: Smaller binaries load faster, improving app startup performance.
  • Improved Performance: The app includes only what’s necessary, reducing overhead.

Example of Tree-Shaking in Action

For suppose, you have following code in Dart:

void usedFunction() {
print("This function is used!");
}

void unusedFunction() {
print("This function is unused!");
}

void main() {
usedFunction();
}

Tree shaking will detect the unused function and compiled build will exclude the “unusedFuntion” from the final output. It also excluded any package or library which you added in your dependency but they are not referenced anywhere in your code.

If you find this article helpful, let’s connect: https://www.linkedin.com/in/syedahmedusman2/

--

--

No responses yet