Sub topic 15
Generating type-safe channel code with Pigeon
This chapter assumes you have finished the earlier chapters. You should know how a MethodChannel carries a method name and arguments to native code, and how the Kotlin and Swift plugin classes answer those calls. Here you replace the hand-written channel code with code generated by Pigeon.
The problem with hand-written channels
In the battery_info plugin, the channel name 'battery_info' and the method string 'getBatteryLevel' appear in three files, one each for Dart, Kotlin and Swift. Nothing checks that they match. Arguments arrive as Object? on the Dart side, as call.arguments in Kotlin, and as Any? in Swift. A typo or a changed argument type fails at runtime, and often only on one platform.
Pigeon is a code generator maintained by the Flutter team. You describe your API once in a Dart file. Pigeon then writes the Dart, Kotlin and Swift code that sends and receives the messages. It still uses platform channels and the standard message codec underneath. It does not replace them.
You gain:
- One source of truth. The channel names and method names are generated, so they cannot drift apart.
- Typed data. You pass classes and enums instead of maps and strings.
- Compile-time errors. If you change a signature and regenerate, the native compilers flag every implementation that no longer matches.
You pay with an extra build step, generated files in your repository, and a dev dependency on pigeon.
Setting up Pigeon
Add Pigeon as a development dependency. It is only needed when you generate code, so consumers of your plugin never download it.
flutter pub add --dev pigeonCreate pigeons/messages.dart at the plugin root. This file is input for the generator only. It is not part of lib/ and is never imported by your plugin.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartPackageName: 'battery_info',
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',
))
enum ChargingState { charging, discharging, full, unknown }
class BatteryStatus {
BatteryStatus({required this.level, required this.state});
/// Battery level as a percentage from 0 to 100.
int level;
ChargingState state;
}
@HostApi()
abstract class BatteryHostApi {
BatteryStatus getStatus();
}The file has three parts:
@ConfigurePigeonnames the output files and the Kotlin package. Pigeon reads the options from this annotation, so you do not need command-line flags.- Data classes and enums are the types that cross the boundary. Pigeon generates a matching class or enum in each language.
@HostApi()marks an interface that is implemented on the native side and called from Dart. "Host" means the Android or iOS app that hosts Flutter.
Generate the code:
dart run pigeon --input pigeons/messages.dartCommit the three generated files. Consumers of your package do not run Pigeon, so the generated code must ship with it. The .g. in the names marks them as generated. Do not edit them, because the next run overwrites your changes.
What gets generated
Pigeon maps your Dart declarations to each language like this:
| Dart definition | Generated Dart | Generated Kotlin | Generated Swift |
|---|---|---|---|
| `class BatteryStatus` | Class with `encode` and `decode` | `data class` | `struct` |
| `enum ChargingState` | Enum | `enum class` with uppercase names | `enum` with an `Int` raw value |
| `int` | `int` | `Long` | `Int64` |
| `@HostApi` interface | Class with `Future` methods | `interface` plus a `setUp` function | `protocol` plus a `...Setup` class |
Check the int row. A Dart int is 64 bits wide, so Pigeon generates Long and Int64. You must convert to and from Int when you work with native APIs, and this is the most common compile error when adopting Pigeon.
Implementing the Kotlin side
The generated Kotlin interface has one method per entry in the host API. Your plugin class implements the interface and registers itself in onAttachedToEngine. You no longer create a MethodChannel or write a when over method names.
package com.example.battery_info
import android.content.Context
import android.os.BatteryManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
class BatteryInfoPlugin : FlutterPlugin, BatteryHostApi {
private lateinit var context: Context
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
BatteryHostApi.setUp(binding.binaryMessenger, this)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
BatteryHostApi.setUp(binding.binaryMessenger, null)
}
override fun getStatus(): BatteryStatus {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level < 0) {
throw FlutterError("UNAVAILABLE", "Battery level not available.", null)
}
val state = if (manager.isCharging) ChargingState.CHARGING else ChargingState.DISCHARGING
return BatteryStatus(level = level.toLong(), state = state)
}
}Two details matter here. Passing null to setUp in onDetachedFromEngine removes the handler, which does the same job as setMethodCallHandler(null) before. FlutterError is a class that Pigeon generates in Messages.g.kt. The generated handler catches anything you throw and sends it to Dart as a PlatformException.
Implementing the Swift side
The Swift side follows the same pattern. The generated protocol declares getStatus() throws -> BatteryStatus, and BatteryHostApiSetup.setUp connects your instance to the channel.
import Flutter
import UIKit
public class BatteryInfoPlugin: NSObject, FlutterPlugin, BatteryHostApi {
public static func register(with registrar: FlutterPluginRegistrar) {
let instance = BatteryInfoPlugin()
BatteryHostApiSetup.setUp(binaryMessenger: registrar.messenger(), api: instance)
}
func getStatus() throws -> BatteryStatus {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryLevel < 0 {
throw PigeonError(code: "UNAVAILABLE", message: "Battery level not available.", details: nil)
}
let state: ChargingState
switch device.batteryState {
case .charging: state = .charging
case .full: state = .full
case .unplugged: state = .discharging
default: state = .unknown
}
return BatteryStatus(level: Int64(device.batteryLevel * 100), state: state)
}
}The error type depends on your Pigeon version. Recent versions generate PigeonError for Swift. Older ones generate FlutterError. Open your generated Messages.g.swift and use the error type declared there.
Using the generated Dart class
The generated Dart class is named BatteryHostApi. Its getStatus method returns a Future<BatteryStatus>. If native code reports an error, the method throws a PlatformException. As in the earlier error-handling chapter, you should not leak that type to your users. Wrap the generated class and keep the public API unchanged:
import 'package:flutter/services.dart';
import 'src/messages.g.dart';
export 'src/messages.g.dart' show BatteryStatus, ChargingState;
class BatteryInfoException implements Exception {
BatteryInfoException(this.code, this.message);
final String code;
final String? message;
@override
String toString() => 'BatteryInfoException($code, $message)';
}
class BatteryInfo {
BatteryInfo({BatteryHostApi? api}) : _api = api ?? BatteryHostApi();
final BatteryHostApi _api;
Future<BatteryStatus> getStatus() async {
try {
return await _api.getStatus();
} on PlatformException catch (e) {
throw BatteryInfoException(e.code, e.message);
}
}
}The constructor accepts an optional BatteryHostApi. That makes the wrapper testable without a device, because a test can pass a fake:
import 'package:battery_info/battery_info.dart';
import 'package:battery_info/src/messages.g.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class FakeHostApi implements BatteryHostApi {
FakeHostApi(this.onGetStatus);
final Future<BatteryStatus> Function() onGetStatus;
@override
Future<BatteryStatus> getStatus() => onGetStatus();
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
void main() {
test('returns the status from the host', () async {
final info = BatteryInfo(
api: FakeHostApi(() async =>
BatteryStatus(level: 42, state: ChargingState.charging)),
);
expect((await info.getStatus()).level, 42);
});
test('wraps PlatformException', () async {
final info = BatteryInfo(
api: FakeHostApi(() async => throw PlatformException(code: 'UNAVAILABLE')),
);
expect(info.getStatus(), throwsA(isA<BatteryInfoException>()));
});
}Pigeon can also generate a test helper through the dartTestOut option. It produces a TestBatteryHostApi class that you attach to the mock binary messenger. Use it when you want to test the generated channel code as well. Injecting a fake, as above, is simpler when you only want to test your own wrapper.
Calling Dart from native code
@HostApi() sends calls from Dart to native code. @FlutterApi() goes the other way. You declare an abstract class, Dart implements it, and native code gets a generated class that calls it. Use it for callbacks that do not fit a stream. For a continuous flow of values, keep using EventChannel, because Pigeon's event support is newer and limited to specific options.
Async methods and supported types
A host method that blocks while it works should be marked @async. The generated Kotlin method then takes a callback: (Result<T>) -> Unit, and the Swift method takes a completion closure. This lets you hop to a background thread and answer later, as described in the threading chapter.
Pigeon supports a fixed set of types:
bool,int,doubleandStringUint8List,Int32List,Int64ListandFloat64ListListandMap, with generic arguments such asList<String?>- enums and your own data classes
It does not support arbitrary classes, DateTime, or Duration. Convert those to int or String yourself.
Common errors
- Forgetting to regenerate. If you change
messages.dartbut not the generated files, the Dart code still compiles. Calls then fail at runtime. Makedart run pigeon --input pigeons/messages.dartpart of your workflow and check it in CI. IntversusLongmismatches. Convert explicitly withtoLong()in Kotlin andInt64(...)in Swift.- Editing generated files. Fix the definition and regenerate instead.
- Mismatched
packageoption. The Kotlinpackagemust equal the package in yourpubspec.yamland your Kotlin directory path. Otherwise the plugin class cannot see the generated types. - Forgetting to unregister. Pass
nulltosetUpinonDetachedFromEngine. Otherwise the handler outlives the engine.
Exercise
You add a String? deviceName field to BatteryStatus in pigeons/messages.dart but do not rerun Pigeon. Does the plugin still compile, and what happens when the Dart code reads deviceName?
Show answer
The plugin still compiles, but deviceName does not exist in the old generated code. If you only edited the definition file, the generated BatteryStatus has no such field, so any Dart code that uses deviceName fails to compile. If you wrote native code against the new field, that code fails too. Either way you must rerun dart run pigeon --input pigeons/messages.dart and commit the regenerated files.
Exercise
Why does the generated Kotlin code use Long for a Dart int, and how do you handle that in your implementation?
Show answer
A Dart int is a 64-bit integer, so Pigeon maps it to Long in Kotlin and Int64 in Swift. In your implementation you convert native Int values with level.toLong() in Kotlin and Int64(value) in Swift, and you convert back with toInt() or Int(value) when you pass the value to native APIs that need Int.