Sub topic 15
Generating Type-Safe Channel Code with Pigeon
This chapter assumes you can write Dart and understand basic Flutter platform channels. You should also know that Android code runs in Kotlin and iOS code runs in Swift. Earlier chapters introduced MethodChannel, where Dart and native code agree on channel and method names manually.
Why use Pigeon?
Pigeon generates channel code from a Dart API definition. You describe methods and data types once, then Pigeon creates matching Dart, Kotlin, and Swift code.
This removes several common sources of channel bugs:
- A misspelled method name.
- A mismatched argument type.
- Different nullability rules on different platforms.
- Repeated message-encoding code.
- Manual
MethodCallHandlerdispatch code.
Pigeon does not remove the platform boundary. It makes the contract across that boundary explicit and generates the repetitive parts.
Define the shared API
Create a file such as pigeons/battery_api.dart. This file is a source definition, not application code that runs directly.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
kotlinOut:
'android/src/main/kotlin/com/example/battery_info/Messages.g.kt',
kotlinOptions: KotlinOptions(
package: 'com.example.battery_info',
),
swiftOut: 'ios/Classes/Messages.g.swift',
))
class PigeonConfig {}
@HostApi()
abstract class BatteryApi {
@async
int getBatteryLevel();
}@HostApi() means that Dart calls an implementation supplied by the host platform. The @async annotation tells Pigeon that the operation completes asynchronously. The generated Dart API exposes a Future<int>-like call, while native implementations receive a completion callback.
Install Pigeon as a development dependency:
dev_dependencies:
pigeon: ^22.0.0Run the generator from the plugin's root directory:
dart run pigeon --input pigeons/battery_api.dartThe generated files should be checked into the package when they are needed to build the plugin. Do not edit them manually. Change the input definition and run Pigeon again.
Implement the generated interfaces
The generated Kotlin and Swift files contain the channel setup and typed method declarations. Your native classes implement the generated API instead of parsing MethodCall objects themselves.
The exact generated class names depend on the Pigeon version and configuration. Inspect the generated files before writing the implementation. A Kotlin implementation will follow this general shape:
class BatteryApiImpl(
private val context: Context,
) : BatteryApi {
override fun getBatteryLevel(result: (Result<Long>) -> Unit) {
val manager =
context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(
BatteryManager.BATTERY_PROPERTY_CAPACITY
)
if (level >= 0) {
result(Result.success(level.toLong()))
} else {
result(Result.failure(BatteryUnavailableException()))
}
}
}Pigeon maps supported Dart types to platform types and generates serialization code. Keep the API model simple. Use nullable fields deliberately, and define data classes for structured values instead of passing loosely shaped maps.
| API definition | Typical generated value |
|---|---|
| `int` | `Int` or `Long` on native platforms |
| `String?` | Nullable string |
| A Pigeon data class | Kotlin data class or Swift class |
| `List<String>` | Typed list |
Trade-offs and errors
Pigeon adds a generation step and generated files to your repository. It also supports fewer arbitrary values than a manually designed channel. In return, the compiler exposes many contract mistakes earlier.
Native failures still cross the channel. Throw or return an error from the native implementation, then convert the generated Dart exception into your plugin's public exception type if callers should not depend on Pigeon's details.
Exercise
Why is changing a Pigeon-generated file directly a poor way to fix a channel API?
Show answer
The next generation run overwrites the change. Update the Dart API definition or the native implementation instead.