Yes, it's possible to avoid duplicating the dependency across flavors, as I describe in my answer here: https://stackoverflow.com/a/75083956/6007104
Utility
Simply add these functions before your dependencies
block:
/** Adds [dependency] as a dependency for the flavor [flavor] */
dependencies.ext.flavorImplementation = { flavor, dependency ->
def cmd = "${flavor}Implementation"
dependencies.add(cmd, dependency)
}
/** Adds [dependency] as a dependency for every flavor in [flavors] */
dependencies.ext.flavorsImplementation = { flavors, dependency ->
flavors.each { dependencies.flavorImplementation(it, dependency) }
}
Usage
You use the utility like this:
dependencies {
...
def myFlavors = ["flavor1", "flavor2", "flavor3"]
flavorsImplementation(myFlavors, "com.example.test:test:1.0.0")
flavorsImplementation(myFlavors, project(':local'))
...
}
How it works
The key to this utility is gradle's dependencies.add
API, which takes 2 parameters:
- The type of dependency, for example
implementation
, api
, flavor1Implementation
. This can be a string, which allows us to use string manipulation to dynamically create this value.
- The dependency itself, for example
"com.example.test:test:1.0.0"
, project(':local')
.
Using this API, you can add dependencies dynamically, with quite a lot of flexibility!