Sub topic 11
Generating Type-Safe Interfaces with Pigeon
Assume you know Dart, Flutter platform channels, and either Kotlin or Swift. You should also know how your Android or iOS host registers a channel handler. This chapter focuses on replacing manually written channel names, method names, and argument maps with generated interfaces.
Why use Pigeon?
A MethodChannel sends method names and loosely typed values at runtime. Dart and native code can disagree about a name or value type, and the compiler usually cannot detect the mistake.
Pigeon is a code-generation tool. You describe an API in Dart, then Pigeon generates matching Dart, Kotlin, and Swift code. The generated code handles message encoding and decoding. Your application code calls methods with declared types.
| Approach | Type checking | Main failure point |
|---|---|---|
| Manual `MethodChannel` | Mostly runtime | Channel names and payload maps |
| Pigeon | Compile time for generated interfaces | Regenerated code and API version mismatches |
Pigeon does not remove the platform channel. It generates a typed layer on top of the channel.
Define the shared API
Create a file such as pigeons/session.dart. The annotations tell Pigeon which methods belong to the host API and where to write generated files.
This example defines a host method that Flutter can call. The method returns a nullable string because a host may not have a signed-in user.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/pigeon/session.g.dart',
kotlinOut: 'android/app/src/main/kotlin/com/example/app/Session.g.kt',
kotlinOptions: KotlinOptions(
package: 'com.example.app',
),
swiftOut: 'ios/Runner/Session.g.swift',
))
@HostApi()
abstract class SessionApi {
String? getUserName();
}Add Pigeon as a development dependency and run the generator from the Flutter module directory:
flutter pub add --dev pigeon
dart run pigeon --input pigeons/session.dartThe generated Dart file contains a SessionApi client. The generated Kotlin and Swift files contain native interfaces and message serializers. Commit the input file and usually the generated files as well. This makes native builds reproducible when another developer has not run the generator locally.
Implement the native side
On Android, implement the generated interface and register it with the binary messenger supplied by the Flutter engine. The exact generated class names depend on your Pigeon version, but the structure is stable:
class SessionApiImpl : SessionApi {
override fun getUserName(): String? = "Ada"
}
// After creating or retrieving the FlutterEngine:
SessionApi.setUp(
engine.dartExecutor.binaryMessenger,
SessionApiImpl()
)On iOS, implement the generated Swift protocol and register the implementation with the engine messenger:
final class SessionApiImpl: SessionApi {
func getUserName() throws -> String? {
return "Ada"
}
}
SessionApiSetup(
binaryMessenger: engine.binaryMessenger,
api: SessionApiImpl()
)Check the generated source for the exact setup function signature. Pigeon output can change between versions, so do not hand-edit generated files.
Call the API from Dart
Import the generated Dart file and use the generated client instead of constructing a channel manually.
import 'package:flutter/material.dart';
import 'pigeon/session.g.dart';
class UserNamePage extends StatelessWidget {
const UserNamePage({super.key});
Future<String> loadName() async {
final name = await SessionApi().getUserName();
return name ?? 'guest';
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: loadName(),
builder: (context, snapshot) {
return Center(child: Text(snapshot.data ?? 'Loading...'));
},
);
}
}Pigeon reports unsupported types during generation rather than waiting for a user to trigger a malformed message. Use simple supported values such as strings, numbers, booleans, lists, maps, and declared data classes. For a larger contract, define a Pigeon class and use it as a request or response type.
Common errors
- Registering the generated API on a different engine from the one displaying the Flutter view.
- Forgetting to regenerate code after changing a method or data type.
- Using different Pigeon versions in different build environments.
- Returning a value that does not match the declared nullable or non-nullable type.
- Calling the API before native setup has completed.
- Editing generated files and losing the change during the next generation run.
Use Pigeon when a channel carries several methods, structured data, or code shared by multiple native targets. A manual channel can remain reasonable for a tiny, private interaction where generation would add more project maintenance than safety.
Exercise
What problem does Pigeon solve when a Flutter method calls native code?
Show answer
It generates matching typed interfaces and serialization code, reducing runtime errors caused by mismatched channel names, method names, and payload types.