Flutter and Android obfuscation

Have you tried Flutter? Yes? good… Now, have you tried to obfuscate Flutter app when compiling for Android?

I will make it brief because there is beautiful weather outside.

Obfuscating and shrinking the APK are those concerns which usually don’t bring much attention until you find it in non-feature requirements of your project.

When it comes to shrinking the code, Dart doesnt need any extra tools to do it. When compiling for release Flutter will take advantage of tree shaking capability of Dart compiler and will drop all unused code. However, Android Java and Kotlin require an extra step. Android build tools provide that step out of the box, but for our use, we will need some additional configuration to protect Flutter wrapper code from being obfuscated or removed.

First, we will enable shrinking and obfuscation in the build file. Find build.gradle file which sits inside /android/app/ folder and add lines in bold

android {

...

buildTypes {

release {

signingConfig signingConfigs.debug

minifyEnabled true
useProguard true

proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'


}
}
}

If we try to compile our project in release mode now, it will inevitably fail. ProGuard which will orchestrate the process for us has to know which classes and members should not be obfuscated or removed.

Next we will create a configuration which will preserve entire Flutter wrapper code. Create /android/app/proguard-rules.pro file and insert inside:

#Flutter Wrapper
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.** { *; }
-keep class io.flutter.util.** { *; }
-keep class io.flutter.view.** { *; }
-keep class io.flutter.** { *; }
-keep class io.flutter.plugins.** { *; }

This configuration will only help Flutter. If you are using any other Android or Java libraries that are susceptible to errors caused by obfuscation or shrinking add them to the file above.

Hope you found this useful and you can now enjoy the sun outside. Our iOS friends are already there, as their platform doesn’t require any code obfuscation.

Written by

Computer enthusiast since 80s, Android developer since Eclair, now Flutter enthusiast. https://gitlab.com/swav-kulinski

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store