Let’s understand Flutter Tree shaking

In this article we will learn about Tree Shaking in flutter which is one of the advance topics of Flutter development. Tree Shaking technology is a Dead Code Elimination technology. It isn’t new, it originated from LISP in the 90s. Google added it to JavaScript in Google Closure Tools first, and later, the dart2js compiler also included it.

This idea of tree shaking is to represent all the execution processes of a program (usually main function) using a tree structure. The main function calls the tree structure and eliminates any code not part of the tree structure. In simpler words, it starts from the main function and creates tree of all the execution paths (functions or calls). The final build removes any code not part of the tree structure, such as unused functions or variables.

In Flutter, we also have the tree shaking mechanism which helps in removing any unused resources. This results in reducing the size of final build and faster load times. It is specially helpful for mobile application since it results in faster installation, quicker startup times and reduced memory footprint.

However, Flutter compiler has different tree shaking optimisations for different build modes. The optimisation only works for release and profile build modes. For debug mode, there is no tree shaking optimisations.

We have created a list of some best practises which will ensure your application is tree shakable :-

  1. Use Const constructor and variables wherever possible – It improve app performance by reducing memory allocation and widget rebuilds, as well as promoting code reusability and making code more concise.
  2. Avoid using dart:mirrors – This library is not tree-shakeable, so it can prevent unused code from being removed.
  3. Lazy loading – Import libraries and resources only when needed.
  4. Avoid using Global variables – Global variables are difficult to shake.
  5. Avoid using Static functions – Static functions are difficult to shake.
  6. Use named constructors – Named constructors are easier to identify which code is used and which isn’t.
  7. Use final variables – Similar to const variables, use final for local variables.
  8. Avoid dynamic codeeval, or Function.apply can’t be tree-shaken, so it’s best to avoid using them.
  9. Use @pragma('dart:developer') to mark unused code – This marks the code for tree shaker to be removed during the tree shaking process.

We found a Flutter Heroes 2023 talk discussing about Flutter Tree Shaking in dept. Please watch the video to understand the concept in detail.

https://www.youtube.com/watch?v=-BnBNKJESkU

External links for further study –

Github Dart SDK Issue

StackOverflow link to check tree shaking in action

Detailed working and example on tree shaking

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *