Sub topic 12
Keeping generated code in sync
This chapter covers what happens after the first run of the generator: where the generated files live, who regenerates them, and how to stop the Dart, Kotlin and Swift sides from drifting apart. It assumes you have a working pigeons/messages.dart input file, you can run dart run pigeon --input pigeons/messages.dart, and you have implemented a HostApi on both platforms as in the earlier chapters.
Why sync is the main maintenance task
Pigeon removes string-based channel names and manual casts, but it adds a new kind of risk. You now have one source file (the schema) and several files derived from it. If the derived files are stale, the compiler on each platform is checking the wrong contract.
Typical symptoms of stale output:
- Dart code calls a method that the generated Dart file does not have yet.
- The Kotlin
BatteryApiinterface has a new method, but the Swift protocol does not, so one platform builds and the other fails. - Both sides compile but were generated by different Pigeon versions, so the wire format differs and calls fail at runtime.
The last case is the only one that fails late. The first two are build errors, which is the behavior you want. The rest of this chapter is about making the third case impossible.
The generated files are build inputs, not build outputs
Pigeon is a development dependency (dev_dependencies). The generated files are ordinary source files that your app compiles. Everyone who builds the app needs them, and a plugin consumer running flutter pub get will not run Pigeon for you.
Each generated file starts with a header like this one:
// Autogenerated from Pigeon (v22.7.0), do not edit directly.
// See also: https://pub.dev/packages/pigeonThe header tells you two things. You must not edit the file, because the next run overwrites your changes. It also records the exact Pigeon version that wrote it, which you can use to find drift.
Commit them or generate in CI?
| Approach | Advantages | Drawbacks |
|---|---|---|
| Commit generated files | Fresh clone builds immediately. Pull requests show the effect of a schema change. Works for published plugins. | Diffs are noisy. Someone can forget to regenerate. |
| Do not commit, generate in every build | No stale files in the repository. | Every build needs Pigeon installed. Native IDEs (Android Studio, Xcode) show errors until you generate. Published plugins break for consumers. |
Commit the generated files. This is the convention in the Flutter plugin ecosystem, and it is the only workable choice for a package you publish. The noise problem is handled by the checks below.
Make regeneration one command
Typing the Pigeon command from memory invites mistakes, especially once you have more than one input file. Put it in a script that lives in the repository.
#!/usr/bin/env bash
# tool/generate_pigeon.sh
set -euo pipefail
cd "$(dirname "$0")/.."
flutter pub get
for input in pigeons/*.dart; do
echo "Generating from $input"
dart run pigeon --input "$input"
doneMake it executable with chmod +x tool/generate_pigeon.sh. Because the output paths are declared inside each input file with @ConfigurePigeon, the script does not need to know about them. Adding a new schema file under pigeons/ is enough.
A short note in the README ("After editing anything in pigeons/, run tool/generate_pigeon.sh and commit the result") covers most of what a team needs.
Pin the Pigeon version
A caret constraint such as pigeon: ^22.7.0 lets pub pick any later 22.x version when someone runs flutter pub upgrade or resolves without a lockfile. Two developers can then generate different code from the same schema. Pigeon releases change generated code often, and some releases change the encoding of messages.
For an app, pubspec.lock is committed and holds the version steady. For a package, the lockfile is usually not committed, so pin the version yourself:
dev_dependencies:
pigeon: 22.7.0Treat a Pigeon upgrade as its own change:
- Change the version in
pubspec.yaml. - Run the generation script.
- Build and run on Android and iOS.
- Commit the version bump and the regenerated files together, in a separate pull request from any schema change.
This keeps the diff readable. Reviewers see either "schema changed" or "generator changed", not both at once.
The day-to-day workflow
Step C is where the type safety pays off. Suppose you add int? temperature to BatteryInfo. After regeneration:
- The Dart
BatteryInfoconstructor and fields includetemperature. - The Kotlin data class has a new
temperature: Long?parameter with a default ofnull? Check your generated file, because the exact shape differs between Pigeon versions. If a constructor call inBatteryApiImplno longer matches, Kotlin reports it at compile time. - The Swift struct initializer changes, and any call that does not pass the new argument fails to compile.
You fix each error, and you cannot ship a platform that silently ignores the new field.
Hot reload does not cover this
Hot reload and hot restart only reload Dart code. After you change a schema, the native side has to be recompiled, so stop the app and run it again. A common confusing error is MissingPluginException or a decoding error right after a schema change, caused by running a new Dart file against an old native binary.
Where the generated files go
The output paths in @ConfigurePigeon decide how the platform toolchains find the files.
- Dart: under
lib/, for examplelib/src/messages.g.dart. Use the.g.dartsuffix so tooling recognizes it as generated. - Kotlin: inside the Android source set, in a directory that matches the
packageyou set inKotlinOptions. A mismatch between the directory and the package causes confusing "unresolved reference" errors. - Swift: in a folder the Xcode project already compiles. Pigeon writes the file but does not edit
project.pbxproj. In an app, a Swift file created outside Xcode must be added to the Runner target once. In a plugin, files underios/Classes/(or the equivalent in your podspec'ssource_files) are picked up automatically.
The Swift case is the most common first-time failure. The generator succeeds, Dart compiles, and Xcode reports Cannot find type 'BatteryApi' in scope. Open Xcode, add Messages.g.swift to the Runner target, and the error disappears. After that, regeneration overwrites the same file and no further Xcode steps are needed.
Keep tools from touching generated files
Two tools tend to fight with generated code.
Formatters. If CI runs dart format --set-exit-if-changed ., it may reformat generated Dart and fail, or a developer's editor may reformat it on save and create diffs that the generator then reverses. Agree on one policy. Either generate and format the same way everywhere, or exclude *.g.dart from format checks. Do not leave it to individual editors.
Analyzers. Generated files can contain code that trips your lint rules. Exclude them in analysis_options.yaml:
analyzer:
exclude:
- "**/*.g.dart"Excluding them from analysis does not exclude them from compilation, so type errors that break your build still show up.
Fail CI when output is stale
Developers forget to regenerate. A CI job that regenerates and then checks for changes catches this for every pull request.
name: pigeon-check
on: [pull_request]
jobs:
generated-code:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: subosito/flutter-action@v2
with:
channel: stable
- name: Regenerate
run: ./tool/generate_pigeon.sh
- name: Fail if generated files changed
run: |
if [ -n "$(git status --porcelain)" ]; then
echo "Generated files are out of date. Run tool/generate_pigeon.sh and commit."
git status --porcelain
exit 1
fiThe check uses git status --porcelain instead of git diff --exit-code. git diff ignores untracked files, so it would miss a brand-new generated file, for example when you add a second input schema.
For this check to be reliable, the job must use the same Flutter and Dart channel as developers, and the Pigeon version must be pinned. Otherwise, the job fails for reasons unrelated to the pull request.
Reviewing a schema change
Generated diffs can be long, so review in this order:
- Read the diff of
pigeons/messages.dart. This is the real change. - Skim the generated files only to confirm they match. Large generated diffs are expected.
- Read the hand-written native implementations carefully. This is where behavior lives.
Some teams mark generated files in .gitattributes so that hosting tools collapse them in reviews:
*.g.dart linguist-generated=true
*.g.kt linguist-generated=true
*.g.swift linguist-generated=trueCommon mistakes
- Editing a generated file to fix a bug. The fix disappears on the next run. Change the schema or the native implementation instead.
- Regenerating only some outputs. Running Pigeon with command-line flags for a single language leaves the other platforms on an old contract. Keep all outputs in
@ConfigurePigeonand run the full command. - Forgetting the rebuild. Hot reload will not pick up native or Swift changes. Do a full run.
- Mixing versions across branches. If one branch bumped Pigeon and another did not, merging gives a mix of generated files. Regenerate after every merge that touched
pigeons/or the Pigeon version. - Renaming a method without a plan. Pigeon derives channel names from the API and method names. A rename is a breaking change for any older native binary that shares the channel, such as a plugin whose Dart and native parts are versioned together. In an app built in one go this is fine, but in a published plugin the Dart and native code ship together, so it is also safe as long as both sides are regenerated.
Exercise
Your team's CI uses git diff --exit-code after running the generator, and it passed on a pull request that added a second schema file pigeons/settings.dart. A teammate later finds that lib/src/settings.g.dart is missing from the repository and the app fails to build on a fresh clone. What went wrong in the check, how do you fix it, and what else should you do to avoid version-related differences between developers' generated output?
Show answer
git diff --exit-code only compares tracked files. The generator created settings.g.dart as a new untracked file, so the diff was empty and the check passed. Replace the check with git status --porcelain (fail if its output is not empty), which also reports untracked files, and commit the missing generated files. To avoid version differences, pin Pigeon to an exact version in dev_dependencies, use the same Flutter channel in CI as locally, and upgrade Pigeon in a separate commit that regenerates every output.