Skip to content

Commit 33f3987

Browse files
Address review: stop reading versionCode, document APK transform failures
- Take the per-ABI versionCode base from a finalizeDsl snapshot of the DSL versionCodes (DslVersionCodes) instead of reading output.versionCode, which AGP rejects during configuration when android.compatibility.enableLegacyApi=false. Warn and skip when the DSL declares no versionCode. - Add a strict-mode (enableLegacyApi=false) case to flutter_build_apk_split_per_abi_test. - CopyFlutterApksTask: use Gradle's Copy/Sync caching annotation and reason; explain when the metadata can be missing and when the ABI check can fail; point both errors at the plugin that transforms SingleArtifact.APK instead of asking for a Flutter issue. - Document what an APK transform must keep in website-page-draft.md. - Link the website-page-draft.md references to tracking issue #193713. - Remove temporal wording from KDoc and docs.
1 parent e15544b commit 33f3987

10 files changed

Lines changed: 437 additions & 115 deletions

File tree

‎docs/platforms/android/Migrating-Flutter-Gradle-Plugin-to-AGP-public-API.md‎

Lines changed: 45 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ Umbrella issues:
1313
The user-facing breaking-change page draft lives next to this file in
1414
[`website-page-draft.md`](website-page-draft.md). It must be published to
1515
`docs.flutter.dev/release/breaking-changes/` before the newDsl flip (phase P9)
16-
reaches the beta channel.
16+
reaches the beta channel. Tracking issue:
17+
https://github.com/flutter/flutter/issues/193713
1718

1819
## Why
1920

@@ -77,21 +78,24 @@ projects. That opt-out dies with AGP 10.
7778
it is seeded with the merged value; set `abiOffset * 1000 + current`,
7879
avoiding a self-referential `.map`. Fall back to a snapshot only if
7980
read-then-set is impossible; record the outcome here.
80-
- *Spike result:* read-then-set works and is what P6 ships
81-
(`configureSplitPerAbiVersionCodes` in `FlutterPlugin.kt`). The plugin reads
82-
`VariantOutput.versionCode.orNull` in `onVariants` and sets
83-
`abiOffset * 1000 + base`. This configuration-time read is a documented exception to
84-
the "no `.get()` at configuration time" rule, because the lazy `.map` form is
85-
circular. No `finalizeDsl` snapshot is needed. See "Features that must break" item 3
86-
for the effect on apps that change `versionCode` in their own `onVariants`.
87-
*Caveat:* the read works only while AGP's compatibility mode is on
88-
(`android.compatibility.enableLegacyApi`, default `true` and deprecated through AGP 9.x).
89-
With it set to `false`, AGP calls `disallowUnsafeRead()` on this property and the read
90-
fails with "configuration of project ':app' has not completed yet". The app-side
91-
`output.versionCode.get()` pattern fails the same way. `Property` has no lazy
92-
self-transform to fall back on. AGP 9.1 marks the option deprecated with
93-
`FeatureStage.Deprecated(VERSION_10_0)`, so re-spike against AGP 10 previews when they
94-
are published. The fallback is the `finalizeDsl` snapshot described above.
81+
- *Spike result:* read-then-set works only while AGP's compatibility mode is on
82+
(`android.compatibility.enableLegacyApi`, default `true` through AGP 9.x and marked
83+
`FeatureStage.Deprecated(VERSION_10_0)`). With it set to `false`, AGP calls
84+
`disallowUnsafeRead()` on `VariantOutput.versionCode` and the read fails with
85+
"configuration of project ':app' has not completed yet". `Property` has no lazy
86+
self-transform to fall back on. AGP deprecates the option for removal in 10.0, and the
87+
[AGP roadmap](https://developer.android.com/build/releases/gradle-plugin-roadmap)
88+
describes AGP 10.0 as completing the move to a fully lazy build model, so P6 does not
89+
depend on the option and ships the `finalizeDsl` snapshot
90+
instead: `DslVersionCodes` reads `defaultConfig.versionCode` and each product
91+
flavor's `versionCode` in `finalizeDsl`, and `configureSplitPerAbiVersionCodes` in
92+
`FlutterPlugin.kt` sets `abiOffset * 1000 + base` without reading the property.
93+
`DslVersionCodes.forVariant` matches AGP's merge (the first flavor in dimension order
94+
that sets a versionCode, then `defaultConfig`). A versionCode set only in the
95+
manifest is not offset, because AGP reads it at execution time. The
96+
`split_per_abi` integration test covers `enableLegacyApi=false`. See "Features that
97+
must break" item 3 for the effect on apps that change `versionCode` in their own
98+
`onVariants`.
9599
5. **`buildModeFor` semantics.** Every variant-scope call uses the
96100
`(name, debuggable)` overload with the public `Component.debuggable`.
97101
Name-based inference is confined to the one DSL-scope case with no public
@@ -119,7 +123,7 @@ projects. That opt-out dies with AGP 10.
119123
| `internal.dsl.BuildType` live aliasing into plugin projects | `PluginHandler.kt` | `initWith`-based copy on new-DSL `BuildType`; app-specific props only when both sides are `ApplicationBuildType` | P3 |
120124
| `BaseExtension` / `getLegacyAndroidExtension` (remaining call sites) | `FlutterPluginUtils.kt` | wrapper accessors incl. `externalNativeBuild` | P4 |
121125
| eager `applicationVariants.configureEach` task creation; mergeAssets/processResources hooks | `FlutterPlugin.kt`, `FlutterPluginUtils.kt` | consolidated `onVariants` block; `CopyFlutterAssetsTask` + `variant.sources.assets.addGeneratedSourceDirectory` | P5 |
122-
| `variant.outputs` + `packageApplicationProvider` + `doLast` APK copy; `versionCodeOverride` | `FlutterPluginUtils.kt` | `CopyFlutterApksTask` (`SingleArtifact.APK` + `BuiltArtifactsLoader`); read-then-set `VariantOutput.versionCode` | P6 |
126+
| `variant.outputs` + `packageApplicationProvider` + `doLast` APK copy; `versionCodeOverride` | `FlutterPluginUtils.kt` | `CopyFlutterApksTask` (`SingleArtifact.APK` + `BuiltArtifactsLoader`); `VariantOutput.versionCode` set from a `finalizeDsl` snapshot (`DslVersionCodes`) | P6 |
123127
| `libraryVariants.all` × host `applicationVariants.all` cross-wiring | `FlutterPlugin.kt` (add-to-app) | library-side `onVariants` with `Component.debuggable`; no host-project lookup | P7 |
124128
| dynamic Groovy legacy API in `aar_init_script.gradle` | `aar_init_script.gradle` | `components`-based enumeration; ext-property guard | P8 |
125129
| `android.newDsl=false` template/migrator | templates, `disable_new_dsl_migration.dart` | drop from templates; `RemoveNewDslOptOutMigration` | P9 |
@@ -189,14 +193,20 @@ else serializes through `FlutterPlugin.kt` / `FlutterPluginUtils.kt`.
189193
the declared outputs and the copied files, and the task fails if AGP built an APK it
190194
did not declare.
191195
3. **Per-ABI versionCode** (`--split-per-abi`): Flutter sets
192-
`VariantOutput.versionCode` in its own `onVariants` callback. AGP runs callbacks in
193-
registration order, so for an app that applies Flutter in its `plugins {}` block,
194-
Flutter's callback runs *before* the app's `androidComponents.onVariants` block.
196+
`VariantOutput.versionCode` in its own `onVariants` callback, from the versionCode the
197+
`android {}` DSL declares for the variant (captured in `finalizeDsl`). It never reads
198+
`output.versionCode`. AGP runs callbacks in registration order, so for an app that
199+
applies Flutter in its `plugins {}` block, Flutter's callback runs *before* the app's
200+
`androidComponents.onVariants` block.
195201
`ApkVariantOutput.versionCodeOverride`, which this replaces, was applied *after* that
196-
block. Apps that set `versionCode` only in the `android {}` DSL see no change. An app
197-
that transforms `output.versionCode` in its own `onVariants` transforms Flutter's
198-
offset value. For example, an app that multiplies by 10000, built with
199-
`--build-number 42`:
202+
block. Apps that set `versionCode` only in the `android {}` DSL see no change. Two
203+
cases change:
204+
- A versionCode declared only in `AndroidManifest.xml`, with none in the DSL, is not
205+
offset. `versionCodeOverride` offset the merged value, which included the manifest.
206+
Flutter's templates set `versionCode = flutter.versionCode` in `defaultConfig`.
207+
- An app that transforms `output.versionCode` in its own `onVariants` transforms
208+
Flutter's offset value. For example, an app that multiplies by 10000, built with
209+
`--build-number 42`:
200210

201211
| ABI (offset) | Before: `offset * 1000 + 42 * 10000` | After: `(offset * 1000 + 42) * 10000` |
202212
| --- | --- | --- |
@@ -206,13 +216,19 @@ else serializes through `FlutterPlugin.kt` / `FlutterPluginUtils.kt`.
206216

207217
In this example the values stay distinct, keep the same ABI order, and only go up, so
208218
Play Store upgrades keep working. Going back to an earlier Flutter release would make
209-
them go down. An app that needs the "Before" numbers can undo Flutter's
210-
offset in its own block before applying its formula:
211-
`base = output.versionCode.get() - offset * 1000`. This only applies when Flutter
212-
applied an offset, so not with `-Pforce-version-code-ignoring-abi=true`.
219+
them go down. An app that needs the "Before" numbers can compute them from its own base
220+
instead of from `output.versionCode`, for example
221+
`output.versionCode.set(offset * 1000 + flutter.versionCode * 10000)` when the base is
222+
the template's `versionCode = flutter.versionCode` (apps with per-flavor versionCodes
223+
use the flavor's value). That form also works with AGP's compatibility mode off, where
224+
reading `output.versionCode` fails.
213225
No runtime divergence warning is emitted. Flutter cannot tell an intended change in
214226
the app's `onVariants` (the pattern AGP recommends) from an unintended one, so a
215-
warning would fire on correct build scripts.
227+
warning would fire on correct build scripts. Flutter does warn when a split-per-abi
228+
variant has no DSL versionCode to offset. The snapshot is taken in Flutter's
229+
`finalizeDsl` callback, so a versionCode change made in a `finalizeDsl` callback
230+
registered after it (for example in the app's build script) is not seen: Flutter offsets
231+
the value from before that change.
216232
4. **Custom build types → plugins**: live-aliased instances become `initWith`
217233
copies; library plugins cannot receive `isDebuggable` (no public setter on
218234
`LibraryBuildType`). **Warning:** If an app uses a custom build type (like `staging`),

‎docs/platforms/android/website-page-draft.md‎

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,20 @@ androidComponents {
8181
}
8282
```
8383

84+
Flutter's copy step reads the APK artifact (`SingleArtifact.APK`) and its
85+
`output-metadata.json` file. If a plugin or your build script transforms that
86+
artifact, the transform must keep the metadata and the APKs' ABI filters:
87+
88+
- Use `toTransformMany(SingleArtifact.APK)` with
89+
`ArtifactTransformationRequest`, which writes the metadata for you, or write
90+
it with `BuiltArtifacts.save()` from a `toTransform` task.
91+
- Produce one APK for each variant output, with the same ABI filter.
92+
93+
Otherwise the build fails with a Flutter error that names `SingleArtifact.APK`.
94+
Fix the transform, or contact the maintainer of the plugin that does it.
95+
Plugins that only read the APK, or that write extra APKs elsewhere after
96+
`assemble`, are not affected.
97+
8498
### Setting per-ABI or per-variant versionCode
8599

86100
Before:
@@ -96,47 +110,51 @@ android.applicationVariants.all { variant ->
96110
After:
97111

98112
```kotlin
113+
import com.android.build.api.variant.FilterConfiguration
114+
99115
androidComponents {
100116
onVariants(selector().all()) { variant ->
101117
variant.outputs.forEach { output ->
102118
val abi = output.filters.find { it.filterType == FilterConfiguration.FilterType.ABI }?.identifier
103-
val base = output.versionCode.orNull ?: 1
104-
output.versionCode.set((abiCodes[abi] ?: 0) * 1000 + base)
119+
output.versionCode.set((abiCodes[abi] ?: 0) * 1000 + flutter.versionCode)
105120
}
106121
}
107122
}
108123
```
109124

125+
Compute the value from a base you already know rather than by reading
126+
`output.versionCode`. AGP disallows reading `output.versionCode` during
127+
configuration when its compatibility mode
128+
(`android.compatibility.enableLegacyApi`) is off. `flutter.versionCode` is the
129+
value Flutter's templates set in `defaultConfig`. If your product flavors set
130+
their own `versionCode`, use the flavor's value for those variants.
131+
110132
Note: For `--split-per-abi` builds, Flutter sets per-ABI version codes
111133
(`abiOffset * 1000 + versionCode`, with offsets 1 for `armeabi-v7a`, 2 for
112-
`arm64-v8a`, and 4 for `x86_64`) in its own `onVariants` callback. When the
113-
Flutter plugin is applied in the `plugins {}` block, as in Flutter's templates,
114-
that callback runs before an `androidComponents.onVariants` block in your app's
115-
build script, so your block sees Flutter's offset value instead of the base
116-
versionCode.
134+
`arm64-v8a`, and 4 for `x86_64`) in its own `onVariants` callback. It takes
135+
`versionCode` from your `android {}` block (`defaultConfig` or a product
136+
flavor). A versionCode set only in `AndroidManifest.xml` is not offset.
137+
When the Flutter plugin is applied in the `plugins {}` block, as in Flutter's
138+
templates, that callback runs before an `androidComponents.onVariants` block
139+
in your app's build script, and a value your block sets replaces Flutter's.
117140
Flutter releases that set `versionCodeOverride` applied the offset after your
118-
block. If your block changes `versionCode`, the result differs from those
119-
releases. For example, multiplying by 10000 with `--build-number 42` gives
120-
`arm64-v8a` the versionCode `20420000`, where those releases gave `422000`. To
121-
keep the `422000`-style numbers, undo Flutter's offset first:
141+
block, so if your block derives `versionCode` from Flutter's value, the result
142+
differs from those releases. For example, multiplying by 10000 with
143+
`--build-number 42` gives `arm64-v8a` the versionCode `20420000`, where those
144+
releases gave `422000`. To keep the `422000`-style numbers, set the value from
145+
`flutter.versionCode` instead:
122146

123147
```kotlin
124148
import com.android.build.api.variant.FilterConfiguration
125149

126150
val flutterAbiOffsets = mapOf("armeabi-v7a" to 1, "arm64-v8a" to 2, "x86_64" to 4)
127-
// Flutter adds its offset only for `--split-per-abi` builds (`-Psplit-per-abi=true`)
128-
// and not when `-Pforce-version-code-ignoring-abi=true` is passed.
129-
val flutterAppliedAbiOffset =
130-
providers.gradleProperty("split-per-abi").orNull.toBoolean() &&
131-
!providers.gradleProperty("force-version-code-ignoring-abi").orNull.toBoolean()
132151

133152
androidComponents {
134153
onVariants(selector().all()) { variant ->
135154
variant.outputs.forEach { output ->
136155
val abi = output.filters.find { it.filterType == FilterConfiguration.FilterType.ABI }?.identifier
137156
val offset = flutterAbiOffsets[abi] ?: 0
138-
val base = output.versionCode.get() - if (flutterAppliedAbiOffset) offset * 1000 else 0
139-
output.versionCode.set(offset * 1000 + base * 10000)
157+
output.versionCode.set(offset * 1000 + flutter.versionCode * 10000)
140158
}
141159
}
142160
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
package com.flutter.gradle
6+
7+
import com.android.build.api.dsl.ApplicationExtension
8+
9+
/**
10+
* The versionCodes an application project declares in its Android DSL, on `defaultConfig` and on
11+
* each product flavor.
12+
*
13+
* Flutter offsets the versionCode of each per-ABI APK from these values instead of reading
14+
* `VariantOutput.versionCode`. AGP disallows reading that property during configuration when its
15+
* compatibility mode (`android.compatibility.enableLegacyApi`) is off, and its lazy form would
16+
* make the property depend on itself. Create an instance with [from] in
17+
* `androidComponents.finalizeDsl`, where the DSL is complete and reading it is supported.
18+
* AGP runs `finalizeDsl` callbacks in registration order, so the snapshot does not see versionCode
19+
* changes made by a `finalizeDsl` callback registered after Flutter's, such as one in the app's
20+
* build script.
21+
*
22+
* @property defaultConfigVersionCode the versionCode set on `defaultConfig`, or null if unset.
23+
* @property productFlavorVersionCodes the versionCode of each product flavor that sets one, keyed
24+
* by flavor name. Flavor names are unique across dimensions, so one map covers all of them.
25+
*/
26+
internal data class DslVersionCodes(
27+
val defaultConfigVersionCode: Int?,
28+
val productFlavorVersionCodes: Map<String, Int>
29+
) {
30+
/**
31+
* Returns the versionCode AGP gives a variant built from [productFlavors], or null if neither
32+
* those flavors nor `defaultConfig` set one.
33+
*
34+
* Matches AGP's merge: the first flavor in [productFlavors] that sets a versionCode wins, and
35+
* `defaultConfig` is the fallback. When the DSL sets no versionCode, AGP reads it from the
36+
* merged manifest instead, which is not available at configuration time.
37+
*
38+
* @param productFlavors the variant's `(dimension, flavor name)` pairs in dimension priority
39+
* order, as returned by `ComponentIdentity.productFlavors`.
40+
*/
41+
fun forVariant(productFlavors: List<Pair<String, String>>): Int? =
42+
productFlavors.firstNotNullOfOrNull { (_, flavorName) -> productFlavorVersionCodes[flavorName] }
43+
?: defaultConfigVersionCode
44+
45+
companion object {
46+
/** Reads the versionCodes declared in [extension]'s DSL. */
47+
fun from(extension: ApplicationExtension): DslVersionCodes =
48+
DslVersionCodes(
49+
defaultConfigVersionCode = extension.defaultConfig.versionCode,
50+
productFlavorVersionCodes =
51+
extension.productFlavors
52+
.mapNotNull { flavor -> flavor.versionCode?.let { flavor.name to it } }
53+
.toMap()
54+
)
55+
}
56+
}

0 commit comments

Comments
 (0)