Sub topic 2
What Pigeon Generates and Why Use It
This chapter explains what Pigeon produces from your input file and what that does to the code you maintain. It assumes you know basic Dart and Flutter structure, async/await, and the idea that Flutter talks to native code through platform channels. You also need to be able to read Kotlin or Swift. Installation and the generator command come in the next chapter. Here the aim is a clear model of the output.
The problem in one example
With a plain MethodChannel, the Dart side and the native side agree on a contract only by convention. The channel name, the method name, the argument keys and the value types are all strings and untyped maps. Nothing checks them at compile time.
import 'package:flutter/services.dart';
const MethodChannel _channel = MethodChannel('com.example.app/battery');
Future<void> printBatteryByHand() async {
final Map<Object?, Object?>? raw =
await _channel.invokeMapMethod<Object?, Object?>('getBatteryInfo');
final int? level = raw?['level'] as int?;
final String? state = raw?['state'] as String?;
print('Battery $level% ($state)');
}Suppose the Kotlin side sends the key "battery_level" instead of "level". This code compiles, runs, and prints Battery null%. Renaming a method on one side only fails at runtime, as a MissingPluginException. Changing a field from int to double on one side surfaces as a cast error, and only on the code path that reads it. The check happens when a user hits the call, not when you build.
What you write: one input file
Pigeon removes this class of bug by making the contract a single source of truth. You describe the API in a Dart file, and Pigeon generates every side from it.
// 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 file has three kinds of content:
- Options in
@ConfigurePigeonsay where each generated file goes and set language-specific details such as the Kotlin package. - Data definitions are plain Dart enums and classes. They describe the values that cross the boundary.
- API definitions are abstract classes marked
@HostApi()or@FlutterApi(). A host API is implemented natively and called from Dart. A Flutter API is implemented in Dart and called from native code.
This file is never compiled into your app. It is only input to the generator, which is why Pigeon is a dev_dependency.
What Pigeon generates
Running the generator writes one file per target language. Each file contains the same contract, expressed in that language's idioms.
| Piece | Dart | Kotlin | Swift |
|---|---|---|---|
| Enum | `enum BatteryState` | `enum class BatteryState` | `enum BatteryState` |
| Data class | `class BatteryInfo` with `encode` and decode | `data class BatteryInfo` | `struct BatteryInfo` |
| HostApi | A client class `BatteryApi` that sends calls | An `interface BatteryApi` you implement | A `protocol BatteryApi` you implement |
| Registration | Not needed, the client just calls | `BatteryApi.setUp(messenger, impl)` | `BatteryApiSetup.setUp(binaryMessenger:api:)` |
| FlutterApi | An abstract class you extend, with `setUp` | A client class that sends calls | A client class that sends calls |
| Codec | A `StandardMessageCodec` subclass that knows your types | The matching codec | The matching codec |
Three points follow from the table.
First, the direction of an API decides which side gets a client and which gets an interface to implement. For a @HostApi(), Dart receives a ready-to-use client class. Kotlin and Swift receive an interface and a registration function. For a @FlutterApi() the roles flip.
Second, the generated data classes are real types in each language. In Dart you read info.level as an int, and in Kotlin as a Long. Dart int is 64-bit, so Pigeon maps it to Long on Kotlin and Int64 on Swift. Forgetting this is a common source of .toLong() compile errors in native implementations.
Third, the codec is generated too. It registers each of your classes and enums with a numeric type tag, so the standard message codec can serialize them. You never write toMap or fromMap by hand.
How the generated code is used
On the Dart side, application code calls a typed method and awaits a typed result.
import 'src/messages.g.dart';
Future<void> printBattery() async {
final api = BatteryApi();
final info = await api.getBatteryInfo();
print('Battery ${info.level}% (${info.state.name})');
}No channel name, no method string, and no cast appears here. Renaming level in the input file and regenerating turns every stale use into a compile error in all three languages.
On the Kotlin side, you implement the generated interface and register it once.
import android.content.Context
import android.os.BatteryManager
class BatteryApiImpl(private val context: Context) : BatteryApi {
override fun getBatteryInfo(): BatteryInfo {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
return BatteryInfo(level = level.toLong(), state = BatteryState.UNKNOWN)
}
}
// In MainActivity:
// override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
// super.configureFlutterEngine(flutterEngine)
// BatteryApi.setUp(flutterEngine.dartExecutor.binaryMessenger, BatteryApiImpl(this))
// }If the input file adds a method to BatteryApi, this class stops compiling until you implement it. Without Pigeon, that mismatch would show up at runtime. Chapter details for registration and the Swift version come later in this tutorial.
What happens at runtime
Pigeon does not replace platform channels. It generates the code that uses them. Under each generated method there is still a BasicMessageChannel, a binary messenger, and a codec.
The generator derives a channel name for each method from the package name, the API class name and the method name, so you never type it. Arguments travel as a list. The reply is a list as well. A successful call carries the result, and a failed call carries an error code, a message and details. The generated Dart client turns that failure list into a PlatformException. The generated native handler catches exceptions from your implementation and builds the failure reply. The exact wire layout is an implementation detail that can change between Pigeon versions, which is another reason to treat the generated files as owned by the tool.
Because the generated code uses the standard channel machinery, it works in apps and in plugins. It also coexists with hand-written channels in the same project.
Why use it: decision criteria
Pigeon pays off when the contract is large or changes often.
- Compile-time safety. Method names, argument types and return types are checked in Dart, Kotlin and Swift.
- One place to change. A new field or method is a few lines in the input file, not three coordinated edits.
- Less boilerplate. You skip hand-written serialization, argument extraction and
switchstatements on method names. - Testability. Dart code depends on a generated class, which you can wrap or fake in tests. A later chapter covers this.
It costs something too:
- You add a build step and generated files to review and commit.
- The input file is a restricted subset of Dart (covered in a later chapter on supported types), so some designs cannot be expressed.
- The generated code is tied to your Pigeon version. Upgrading Pigeon can change the generated files and sometimes the native signatures you implement.
A reasonable rule: for one method that passes a string, a hand-written MethodChannel is fine. Once you have several methods, structured data, or native code that calls back into Dart, Pigeon is usually the cheaper option to maintain.
Common gotchas
- Mixed-up directions. Annotating an API
@HostApi()when native code needs to call Dart gives you the wrong generated shape. Ask who implements the method. The implementer decides the annotation. - Stale generated files. If you change the input file and forget to regenerate, the three languages disagree with the file but still agree with each other. The bug looks like a missing feature, not a type error.
- Integer width. Dart
intis 64-bit. Native code getsLongorInt64, so values from native APIs that returnIntneed a conversion. - Missing registration. The generated interface compiles whether or not you call
setUp. If you skip registration, Dart calls fail at runtime because no handler is listening on the channel.
Exercise
A teammate renames the field level to percent in BatteryInfo inside pigeons/messages.dart and regenerates. Where does the mismatch show up, and how would the same rename behave with a hand-written MethodChannel that sends a map with the key "level"?
Show answer
With Pigeon, regenerating changes the Dart, Kotlin and Swift classes together. Every use of level in app code and in BatteryApiImpl becomes a compile error, so you find and fix all of them before running the app. With the hand-written channel, renaming the key on one side only compiles fine and returns null for the field at runtime, so the bug appears only when that code path runs.
Exercise
You need native Android code to notify Dart whenever the battery state changes. Which annotation do you use for the API, which side implements it, and which side gets the generated client class?
Show answer
Use @FlutterApi(). Dart implements the generated abstract class and registers it with setUp. The Kotlin side gets the generated client class and calls it to send the notification to Dart.