Skip to content

Commit 8608bc9

Browse files
reidbaker-agentsuryaKommana2662
authored andcommitted
[AGP 9.1.0 Migration flutter#7] Migrate the flutter-apk copy and per-ABI versionCode to the variant API (flutter#193693)
## Description This is PR 7 of 11 in the AGP 9.1.0 / public `gradle-api` migration stack ([flutter#180137](flutter#180137), [flutter#166550](flutter#166550)). This pr changes the way splitting by api version codes work. This can be a surprising change but I have not found a work around. PR 8 adds add-to-app support and as a result deletes a bunch of code that exists to bridge the partial migration. See flutter#19371 specifically https://github.com/flutter/flutter/pull/193717/changes/f668780fd47caca13c03828f49d21572074825d6..a6be16034c8a1a4a0456cd35194b5973cfd4dc75#r4185414230 which is a subset of changes. <details> <summary>Agent authored details</summary> ### Changes 1. **flutter-apk copy on the variant API.** `CopyFlutterApksTask` (`copyFlutterApks<Variant>`) copies the variant's `SingleArtifact.APK` outputs, read through `BuiltArtifactsLoader`, into `build/app/outputs/flutter-apk/`. The names are `app[-abi][-flavor]-<mode>.apk`, the format `listApkPaths` in `lib/src/android/gradle.dart` expects. `assemble<Variant>` depends on the task. - The task has no `Project` or variant fields. It uses injected `FileSystemOperations` and `@InputDirectory @PathSensitive(RELATIVE)`. - It is annotated `@DisableCachingByDefault(because = "Not worth caching")`, the annotation and reason Gradle uses on its own `Copy` and `Sync` tasks. - Its declared outputs are the individual APK files (`@OutputFiles`). The shared `flutter-apk` directory is not declared, because it would overlap between variants. - One naming function, `CopyFlutterApksTask.apkFileName`, produces both the declared outputs and the copied files. Its inputs are the ABIs of the variant's outputs, the flavor, and the build mode. 2. **Per-ABI versionCode without reading `output.versionCode`.** For `--split-per-abi`, the plugin sets `output.versionCode = ABI_VERSION[abi] * 1000 + base` on each `ApplicationVariant` output with an ABI filter. It never reads the property, because AGP rejects that read during configuration when `android.compatibility.enableLegacyApi=false`. - `DslVersionCodes` takes a snapshot of `defaultConfig.versionCode` and each product flavor's `versionCode` in `androidComponents.finalizeDsl`. - `forVariant(variant.productFlavors)` resolves the base the way AGP merges it: the first flavor, in dimension order, that sets a versionCode, otherwise `defaultConfig`. - If the DSL declares no versionCode, Flutter logs a warning and leaves the variant's versionCodes unchanged. 3. **APK transform errors point at the transform.** The copy fails in two cases. Both can happen only if another plugin or build script transforms `SingleArtifact.APK`: - the APK directory has no `output-metadata.json`; - an APK has an ABI filter that none of the variant's outputs declares. Both error messages name `SingleArtifact.APK` and tell the user to contact the maintainer of the plugin that does the transform. They do not ask for a Flutter issue. The task KDoc and `website-page-draft.md` say what a transform must keep. Plugins Flutter developers commonly use (Walle, VasDolly, packer-ng, AndResGuard, Sentry, Firebase App Distribution, Gradle Play Publisher) do not trigger either error; the evidence is in [this review reply](flutter#193693 (comment)). 4. **Deleted** the app-path `applicationVariants.configureEach` block and `configureAbiVersionCodeOverride`, together with their two `@Suppress("DEPRECATION")` markers and the unsafe `as ApkVariantOutput` cast. The add-to-app module path (`addFlutterDepsForModule`, `libraryVariants`) is left for PR 8. 5. **Structure follows the PR 6 review** (@mboetger's point that `registerFlutterAssetTasks` should not register the compile task). `onVariants` calls `configureSplitPerAbiVersionCodes` and `registerCopyFlutterApksTask` after `registerFlutterAssetTasks`, under the same `isApplicationProject && shouldCompileFlutterForVariant` gate. Each helper does one job, and no helper takes a parameter only to pass it on. 6. **Docs:** - `Migrating-Flutter-Gradle-Plugin-to-AGP-public-API.md`: decision record 4, the replacement map, and items 2 and 3 of "Features that must break". - `website-page-draft.md`: versionCode recipes that do not read `output.versionCode`, and the rules for APK transforms. - Links to the draft carry a TODO for [flutter#193713](flutter#193713), which tracks publishing it on docs.flutter.dev. 7. **Tests:** - `CopyFlutterApksTaskTest` (new, 5 tests). - `DslVersionCodesTest` (new, 5 tests). - 8 new `FlutterPluginTest` cases: defaultConfig and flavor offsets, the no-versionCode warning, no split, the force flag, copy wiring, profile/custom build type naming, and assemble wiring. The mocked `VariantOutput.versionCode` stubs only `set`, so any read fails the test. - `flutter_build_apk_split_per_abi_test.dart`: a fourth test builds with `android.compatibility.enableLegacyApi=false`, and every test asserts each per-ABI APK is in `flutter-apk`. ### Review response (commit `33f39876b92`) | Comment | Change | | --- | --- | | Caching annotation: "How do I know this is true?" | Uses Gradle's own `Copy`/`Sync` annotation and reason (checked with `javap`). | | Why would `load` return null? / How would ABIs mismatch? | Comments say exactly when each can happen. Errors point at the plugin that transforms the APK. | | Other places that build APK names | FGP has one. The tool's three reading sites are listed in the reply (ratchet: not changed here). | | Custom variants, and proof the copy works | Build-mode rule matches the deleted code. Results of a flavor and custom build type scratch app are in the reply. | | Temporal wording | Removed from KDoc and docs. | | Link to the website docs | TODO tied to flutter#193713 until the page is published. | | Reading `output.versionCode` depends on compatibility mode | No read. `finalizeDsl` snapshot instead, with a compatibility-mode-off integration test. | | Why ×10000, and can the earlier numbers be kept? | Explained in the replies. Keeping them requires reading the value the app set, which AGP rejects with compatibility mode off. | ### Why removing the deleted code is safe The deleted code used `AbstractAppExtension.applicationVariants`, `ApkVariantOutput.versionCodeOverride`/`getFilter`, and `packageApplicationProvider`. AGP deprecated these, and they are not available with AGP 9's `android.newDsl=true`. The replacements (`ApplicationVariant.outputs`, `VariantOutput.versionCode`/`filters`, `SingleArtifact.APK`, `BuiltArtifactsLoader`, `DslLifecycle.finalizeDsl`) are public `com.android.build.api` APIs available at the stack's AGP 8.11.1 floor. ### Behavioral and compatibility notes 1. **versionCode for apps that transform it in their own `onVariants` (breaking).** Flutter registers its `onVariants` callback when the plugin is applied, so AGP runs it before an app's `androidComponents.onVariants` block. `versionCodeOverride` was applied after that block. Apps that set `versionCode` only in the `android {}` DSL see no change. An app that multiplies by 10000 (compatibility mode on), built with `--build-number 42`: | ABI (offset) | `versionCodeOverride` | This PR | | --- | --- | --- | | `armeabi-v7a` (1) | 421000 | 10420000 | | `arm64-v8a` (2) | 422000 | 20420000 | | `x86_64` (4) | 424000 | 40420000 | Values stay distinct, keep ABI order, and only go up, so Play upgrades keep working. With compatibility mode off, apps can't read `output.versionCode` either. For that case the docs give a recipe that sets an absolute value in the app's `onVariants`, which replaces Flutter's: `offset * 1000 + flutter.versionCode * 10000`. 2. **A versionCode declared only in the manifest is not offset.** The DSL snapshot can't see it, so Flutter logs a warning and leaves the variant's versionCodes unchanged. 3. **A `finalizeDsl` callback registered after Flutter's that changes versionCode is not seen.** This is documented in the `DslVersionCodes` KDoc and the migration doc. 4. **`copyFlutterApks<Variant>` tasks appear in `gradlew tasks`** and can be UP-TO-DATE. 5. **Two build types that map to the same Flutter mode share a file name.** For example, `debug` and a debuggable `staging` both write `app-debug.apk`; the deleted code had the same clash. Running both assembles in one `./gradlew` invocation makes the two copy tasks alternate. The `flutter` tool builds one variant per invocation, so it is unaffected. ### Integration test coverage of the changed paths | Path | Tests | | --- | --- | | Per-ABI versionCode: default, build number, app `onVariants` transform, compatibility mode off | `flutter_build_apk_split_per_abi_test.dart` (4 tests; checks versionCodes with `apkanalyzer` and the per-ABI files in `flutter-apk`) | | flutter-apk copy, default and flavored | `android_gradle_asset_merging_test.dart`, `gradle_libapp_so_packaging_test.dart` (incl. flavors), `android_plugin_example_app_build_test.dart`, `isolated/native_assets_flutter_build_test.dart`; devicelab `flavors_test`, `gradle_desugar_classes_test` | | Plugin unit tests on AGP 8.11.1 and AGP 9 | `android_run_flutter_gradle_plugin_tests_test.dart` | ### Tests run locally - `./gradlew test` in `packages/flutter_tools/gradle` (JDK 17): pass (33 suites, 0 failures). - ktlint 1.5.0 with the CI `.editorconfig` and baseline: clean. - `dart format` / `dart analyze --fatal-infos` on the changed Dart test: clean. - `flutter_build_apk_split_per_abi_test` on `33f39876b92`: 4/4 pass. - On the review changes before the final edits to comments and error messages: `android_gradle_asset_merging_test` (4), `gradle_libapp_so_packaging_test` (4), `android_run_flutter_gradle_plugin_tests_test` (2) all pass. - Manual build with `enableLegacyApi=false` (AGP 9.3.1): versionCodes 1042/2042/4042. A negative control that re-adds the read fails with "configuration of project ':app' has not completed yet". - Scratch app with `free`/`paid` flavors and a custom `staging` build type: APK names and versionCodes match the deleted code. </details> --- ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent 041e88f commit 8608bc9

12 files changed

Lines changed: 1014 additions & 121 deletions

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

Lines changed: 67 additions & 8 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,7 +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:* _pending (P6)_.
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`.
8199
5. **`buildModeFor` semantics.** Every variant-scope call uses the
82100
`(name, debuggable)` overload with the public `Component.debuggable`.
83101
Name-based inference is confined to the one DSL-scope case with no public
@@ -105,7 +123,7 @@ projects. That opt-out dies with AGP 10.
105123
| `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 |
106124
| `BaseExtension` / `getLegacyAndroidExtension` (remaining call sites) | `FlutterPluginUtils.kt` | wrapper accessors incl. `externalNativeBuild` | P4 |
107125
| eager `applicationVariants.configureEach` task creation; mergeAssets/processResources hooks | `FlutterPlugin.kt`, `FlutterPluginUtils.kt` | consolidated `onVariants` block; `CopyFlutterAssetsTask` + `variant.sources.assets.addGeneratedSourceDirectory` | P5 |
108-
| `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 |
109127
| `libraryVariants.all` × host `applicationVariants.all` cross-wiring | `FlutterPlugin.kt` (add-to-app) | library-side `onVariants` with `Component.debuggable`; no host-project lookup | P7 |
110128
| dynamic Groovy legacy API in `aar_init_script.gradle` | `aar_init_script.gradle` | `components`-based enumeration; ext-property guard | P8 |
111129
| `android.newDsl=false` template/migrator | templates, `disable_new_dsl_migration.dart` | drop from templates; `RemoveNewDslOptOutMigration` | P9 |
@@ -165,11 +183,52 @@ else serializes through `FlutterPlugin.kt` / `FlutterPluginUtils.kt`.
165183
APK-rename recipes) fail under newDsl — the biggest break. Mitigated by new
166184
error handlers (P9) and the website page.
167185
2. **flutter-apk copy**: same names/paths (`app[-abi][-flavor]-<mode>.apk`,
168-
byte-matching the current concatenation order), but an UP-TO-DATE-capable
169-
finalizer task replaces the `doLast` block; new task names appear in
170-
`gradlew tasks`.
171-
3. **Per-ABI versionCode**: post-`finalizeDsl` user mutations (`afterEvaluate`
172-
CI patterns) may behave differently; a runtime divergence warning is added.
186+
byte-matching the order `listApkPaths` in the Flutter tool expects). `CopyFlutterApksTask`
187+
(`copyFlutterApks<Variant>`, which `assemble<Variant>` depends on) replaces the
188+
`doLast` block, so `copyFlutterApks<Variant>` tasks appear in `gradlew tasks`. It reads
189+
`SingleArtifact.APK` through `BuiltArtifactsLoader`. Its declared outputs are the
190+
individual APK files rather than the shared `flutter-apk` directory, which would
191+
overlap between variants. The file names come from the variant's outputs (the APKs
192+
AGP will build), not from `target-platform`. A single naming function produces both
193+
the declared outputs and the copied files, and the task fails if AGP built an APK it
194+
did not declare.
195+
3. **Per-ABI versionCode** (`--split-per-abi`): Flutter sets
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.
201+
`ApkVariantOutput.versionCodeOverride`, which this replaces, was applied *after* that
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`:
210+
211+
| ABI (offset) | Before: `offset * 1000 + 42 * 10000` | After: `(offset * 1000 + 42) * 10000` |
212+
| --- | --- | --- |
213+
| `armeabi-v7a` (1) | 421000 | 10420000 |
214+
| `arm64-v8a` (2) | 422000 | 20420000 |
215+
| `x86_64` (4) | 424000 | 40420000 |
216+
217+
In this example the values stay distinct, keep the same ABI order, and only go up, so
218+
Play Store upgrades keep working. Going back to an earlier Flutter release would make
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.
225+
No runtime divergence warning is emitted. Flutter cannot tell an intended change in
226+
the app's `onVariants` (the pattern AGP recommends) from an unintended one, so a
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.
173232
4. **Custom build types → plugins**: live-aliased instances become `initWith`
174233
copies; library plugins cannot receive `isDebuggable` (no public setter on
175234
`LibraryBuildType`). **Warning:** If an app uses a custom build type (like `staging`),

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

Lines changed: 57 additions & 8 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,23 +110,58 @@ android.applicationVariants.all { variant ->
96110
After:
97111

98112
```kotlin
113+
import com.android.build.api.variant.FilterConfiguration
114+
115+
androidComponents {
116+
onVariants(selector().all()) { variant ->
117+
variant.outputs.forEach { output ->
118+
val abi = output.filters.find { it.filterType == FilterConfiguration.FilterType.ABI }?.identifier
119+
output.versionCode.set((abiCodes[abi] ?: 0) * 1000 + flutter.versionCode)
120+
}
121+
}
122+
}
123+
```
124+
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+
132+
Note: For `--split-per-abi` builds, Flutter sets per-ABI version codes
133+
(`abiOffset * 1000 + versionCode`, with offsets 1 for `armeabi-v7a`, 2 for
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.
140+
Flutter releases that set `versionCodeOverride` applied the offset after your
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:
146+
147+
```kotlin
148+
import com.android.build.api.variant.FilterConfiguration
149+
150+
val flutterAbiOffsets = mapOf("armeabi-v7a" to 1, "arm64-v8a" to 2, "x86_64" to 4)
151+
99152
androidComponents {
100153
onVariants(selector().all()) { variant ->
101154
variant.outputs.forEach { output ->
102155
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)
156+
val offset = flutterAbiOffsets[abi] ?: 0
157+
output.versionCode.set(offset * 1000 + flutter.versionCode * 10000)
105158
}
106159
}
107160
}
108161
```
109162

110-
Note: Flutter itself sets per-ABI version codes for `--split-per-abi` inside
111-
`onVariants`. If your CI mutates version codes in `afterEvaluate`, that runs at
112-
a different time than before; Flutter prints a warning when it detects a
113-
divergence between the DSL value and the final output value. To verify your
114-
mutations worked, inspect the built APK:
115-
`apkanalyzer manifest print versionCode build/app/outputs/flutter-apk/app-release.apk`
163+
To verify the result, inspect the built APK:
164+
`apkanalyzer manifest print versionCode build/app/outputs/flutter-apk/app-arm64-v8a-release.apk`
116165

117166
### Custom build types and plugins
118167

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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 declared on `defaultConfig` and on each product flavor.
11+
*
12+
* Flutter computes per-ABI versionCodes from these instead of reading `VariantOutput.versionCode`,
13+
* which AGP rejects during configuration when `android.compatibility.enableLegacyApi=false`.
14+
* Create it with [from] in `finalizeDsl`. It does not see changes made by `finalizeDsl` callbacks
15+
* registered after Flutter's.
16+
*
17+
* @property productFlavorVersionCodes keyed by flavor name, which is unique across dimensions.
18+
*/
19+
internal data class DslVersionCodes(
20+
val defaultConfigVersionCode: Int?,
21+
val productFlavorVersionCodes: Map<String, Int>
22+
) {
23+
/**
24+
* The versionCode AGP merges for a variant: the first of [productFlavors] (in dimension
25+
* priority order) that sets one, else `defaultConfig`. Null if none is set in the DSL.
26+
*/
27+
fun forVariant(productFlavors: List<Pair<String, String>>): Int? =
28+
productFlavors.firstNotNullOfOrNull { (_, flavorName) -> productFlavorVersionCodes[flavorName] }
29+
?: defaultConfigVersionCode
30+
31+
companion object {
32+
/** Reads the versionCodes declared in [extension]'s DSL. */
33+
fun from(extension: ApplicationExtension): DslVersionCodes =
34+
DslVersionCodes(
35+
defaultConfigVersionCode = extension.defaultConfig.versionCode,
36+
productFlavorVersionCodes =
37+
extension.productFlavors
38+
.mapNotNull { flavor -> flavor.versionCode?.let { flavor.name to it } }
39+
.toMap()
40+
)
41+
}
42+
}

0 commit comments

Comments
 (0)