Product flavors are a powerful feature of the Gradle plugin from Android Studio to create customised versions of products. They form part of what we call Build Variants.
Build Variants are formed by Build Types and Product Flavors.
According to the Google documentation, build variants are the result of Gradle using a specific set of rules to combine settings, code, and resources configured in your build types and product flavors.
Build Type applies different build and packaging settings. An example of build types are “Debug” and “Release”.
Product Flavors specify different features and device requirements, such as custom source code, resources, and minimum API levels.
Why Product Flavors?
- They address the issue of having separate project code for each version of the app while still having one project code.
- Given a scenario where you have a free and a paid app you can limit features in the free and expose all the other features in the paid version of the app.
- Given another scenario where you want to implement region-specific functions depending on the country, you can use product flavors for such a use case.
- White labeling (these are apps that are developed by a certain company, and they are re-branded and resold by other companies).
Pros
They address the issue of having a separate project code base for each version of the app.
They keep the code tidy and makes it much easier and faster to navigate through the code base as everything related to the specific product flavor would be kept in their corresponding folders.
Cons
(Scaling Up) The more variants, the greater the complexity which thereby makes it harder to maintain the codebase.
IDEs sometimes takes time to build the project after switching between variants.
Here is an example:
android {
...
defaultConfig {...}
buildTypes {...}
flavorDimensions "icecream"
productFlavors {
strawberry {
dimension "icecream"
applicationIdSuffix ".strawberry"
}
chocolate {
dimension "icecream"
applicationIdSuffix ".chocolate"
}
vanilla {
dimension "icecream"
applicationIdSuffix ".vanilla"
}
}