Sub topic 3
Adding Pigeon and generating code
This chapter takes a Flutter project from no Pigeon to generated Dart, Kotlin and Swift files that compile. You will add the dependency, place the input file, set the output paths, run the generator and wire the results into each platform project. The API design itself (data types, HostApi, FlutterApi) comes in later chapters. Here the schema stays small so the setup is the focus.
What you need before starting
This chapter assumes you already have:
- A Flutter app or plugin that builds for Android and iOS.
- A working idea of how
MethodChannelcalls pass through the engine's binary messenger. The previous chapters covered this. - Enough Kotlin and Swift to read a class that implements an interface or protocol.
- A terminal opened at the root of the Flutter package, the folder that contains
pubspec.yaml.
Add Pigeon as a development dependency
Pigeon is a build-time tool. The app ships only the files it generates, and those depend on flutter/services.dart and the platform Flutter embedding, not on Pigeon. So Pigeon goes under dev_dependencies.
dev_dependencies:
pigeon: ^latest_versionReplace ^latest_version with the current release from pub.dev. The simplest way is to let the tool pick it:
flutter pub add dev:pigeonPigeon's version is not a detail you can ignore. Each generated file records the Pigeon version that produced it, and the generated Dart, Kotlin and Swift code agree on a binary encoding that the generator defines. The three outputs must therefore come from the same run. Never regenerate only one platform after upgrading Pigeon.
Where the input file lives
The input file is ordinary Dart, but it is not part of your app. Put it in a top-level pigeons/ folder, outside lib/:
my_app/
pigeons/
messages.dart <- you write this
lib/
android/
ios/
pubspec.yamlKeeping it out of lib/ matters for two reasons. It is never imported by app code, and it declares abstract methods and annotations that exist only to describe an API. Those declarations should not end up in your app bundle.
Describe the outputs in the input file
The input file carries its own configuration in a @ConfigurePigeon annotation placed before the first declaration. Here is the file from the plan:
// pigeons/messages.dart
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
kotlinOut: 'android/app/src/main/kotlin/com/example/app/Messages.g.kt',
kotlinOptions: KotlinOptions(package: 'com.example.app'),
swiftOut: 'ios/Runner/Messages.g.swift',
))
enum BatteryState { charging, discharging, full, unknown }
class BatteryInfo {
BatteryInfo({required this.level, required this.state});
int level;
BatteryState state;
}
@HostApi()
abstract class BatteryApi {
BatteryInfo getBatteryInfo();
}The annotation is attached to the BatteryState enum only because an annotation must sit on some declaration. It applies to the whole file.
The table lists the options used here.
| Option | Meaning |
|---|---|
| `dartOut` | Path of the generated Dart file, relative to the directory where you run the command. |
| `kotlinOut` | Path of the generated Kotlin file. |
| `kotlinOptions` | Kotlin settings. `package` is written as the first line of the Kotlin file. |
| `swiftOut` | Path of the generated Swift file. |
Pigeon can also generate Java, Objective-C, C++ and GObject output through similar options. Only produce the languages your app actually builds. Unused outputs add files that still need maintenance.
Choosing paths and the package name
The Kotlin package value must match the package of the Android code that will use the generated file, normally the applicationId namespace of MainActivity. The folder under kotlin/ should match it too: com.example.app belongs in com/example/app/. Kotlin does not strictly require folders to mirror packages, but Android Studio and most tooling expect it.
For a plugin rather than an app, the paths differ. Android output typically goes under android/src/main/kotlin/<your/package>/ and iOS output under ios/<plugin_name>/Sources/<plugin_name>/ or ios/Classes/, depending on how the plugin is packaged. Check where your plugin's other Swift files live and put the generated file beside them.
The suffix .g.dart, .g.kt and .g.swift is a convention that marks a file as generated. Keep it. It lets tools and teammates recognise files that must not be edited.
Run the generator
From the package root:
dart run pigeon --input pigeons/messages.dartThis reads the input file, validates the schema and writes every output named in the annotation. It runs on every invocation and overwrites the existing files. There is no incremental mode and no watcher, so you rerun it by hand whenever the input changes.
You can also pass paths on the command line instead of in the annotation, for example --dart_out and --kotlin_out. Command-line flags are useful for one-off experiments. For a real project, keep the options in the annotation, because they are versioned with the schema and everyone gets the same result. Run dart run pigeon --help to see the full flag list for your installed version.
Paths are resolved relative to the directory you run the command from, not relative to the input file. Running it from a subfolder is the most common reason files appear in the wrong place.
The next diagram shows the flow.
What each generated file contains
Open each output once. You will not edit them, but knowing what is inside makes errors easier to read.
- Dart file: the data classes and enums, a codec that serialises them, and one class per
@HostApi()that exposes each method as aFuture. Each method sends a message over a channel whose name Pigeon builds from the API and method names. - Kotlin file: the same data classes and enums, an interface for each
HostApithat you implement, and asetUpfunction that registers your implementation on aBinaryMessenger. - Swift file: equivalent structs or classes, a protocol for each
HostApi, and a setup class that registers your implementation.
All three carry a header saying the file is generated and which Pigeon version wrote it. The channel names and the codec are the part that used to be hand-written strings in MethodChannel code. Because one run writes both ends, they cannot disagree.
Keep generated Dart out of analysis noise
Generated code may not follow your lint rules. Pigeon adds ignore_for_file comments for most cases, but you can also exclude the generated files from the analyzer so lints do not fire on code you do not own:
# analysis_options.yaml
analyzer:
exclude:
- "**/*.g.dart"Excluding a file from analysis does not stop it from compiling, and your own code that imports it is still checked against its real types.
Connect the generated code to each platform
Generation only creates the files. Registration still has to happen on each side, which the next chapter covers in full. Setup, though, has two gotchas that belong here.
Android
A Kotlin file inside android/app/src/main/kotlin/ is compiled automatically. Confirm the package line matches the folder and that your implementation class imports nothing else from Pigeon. The generated file references io.flutter.plugin.common classes, which are already available through the Flutter embedding.
iOS
A new Swift file in ios/Runner/ is not automatically part of the Xcode project. If the file exists on disk but is not listed in the Runner target, the build fails with errors such as "cannot find type 'BatteryApi' in scope". Open ios/Runner.xcworkspace in Xcode, add Messages.g.swift to the Runner target once, and commit the project file change. After that, rerunning Pigeon only overwrites the file's contents, so you do not need to add it again.
Plugins that use CocoaPods or Swift Package Manager pick up files from their source folder by path, so this step usually does not apply to them.
A repeatable command
Typing the command from memory invites mistakes. A small script puts the working directory and the command in one place:
#!/usr/bin/env bash
# tool/generate.sh
set -euo pipefail
cd "$(dirname "$0")/.."
flutter pub get
dart run pigeon --input pigeons/messages.dartMake it executable with chmod +x tool/generate.sh, then run ./tool/generate.sh from anywhere. Because the script changes into the package root first, relative output paths always resolve the same way. If your project has several input files, add one dart run pigeon line per file. Each file needs its own distinct output paths, or the later run overwrites the earlier one.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Generated files appear in an unexpected folder, or the command cannot find the input | The command ran from the wrong directory | Run from the package root, or use the script above. |
| `Unresolved reference` or `package does not match` in Kotlin | `KotlinOptions(package: ...)` differs from the app's package | Make the package match, or move the file to the matching folder. |
| Xcode cannot find the generated types | `Messages.g.swift` was never added to the Runner target | Add it in Xcode once. |
| Dart and native code disagree after an upgrade | Only some outputs were regenerated | Rerun the generator so all outputs come from one run. |
| The command fails on the schema | The input uses a type or construct Pigeon does not support | Read the error text, then simplify the declaration. Supported types are covered in a later chapter. |
| Your edits to a `.g` file disappear | The next generator run overwrote them | Change the input file instead, and regenerate. |
Check your setup
A quick way to confirm everything works is to compile each platform before you write any implementation:
- Run the generator and check that the three files exist.
- Run
flutter analyze. The generated Dart file should add no errors. - Build for Android. The generated Kotlin interface compiles even though nothing implements it yet.
- Build for iOS. A missing target membership shows up here.
The build still succeeds, because generated interfaces are only declarations. They do nothing until you register an implementation. Calling BatteryApi().getBatteryInfo() at this stage would fail at runtime on the platform side, since nothing is listening on that channel. That runtime failure is expected, and the next chapters resolve it.
Exercise
You added Pigeon, ran dart run pigeon --input pigeons/messages.dart from inside the lib/ folder, and the Dart file was written to lib/lib/src/messages.g.dart. What went wrong, and how do you prevent it from happening again?
Show answer
Output paths such as lib/src/messages.g.dart are resolved relative to the directory where the command runs, not relative to the input file. Running from lib/ therefore prefixed the path with lib/. Run the command from the package root, which also means the input path is correct. A script such as tool/generate.sh that does cd "$(dirname "$0")/.." first makes the result independent of where you call it. Delete the stray lib/lib/ folder and rerun.
Exercise
A teammate upgrades Pigeon, regenerates only the Dart file, and commits it. What risk does this create, and what should they have done?
Show answer
The Dart and native files share a message encoding defined by the generator version. If the Dart side is newer than the Kotlin and Swift sides, the two ends may encode or decode messages differently, and calls can fail or return wrong data at runtime. They should rerun the generator so Dart, Kotlin and Swift are all written from one run, then commit all outputs together.