Sub topic 11
Generating type-safe interfaces with Pigeon
The earlier chapter on platform channels used MethodChannel with string method names and untyped arguments. That works, but each side has to agree on names, argument order, and types without any compiler checking it. This chapter assumes you have a working module, a host app that runs a cached FlutterEngine, and a MethodChannel call like getUserName from the earlier chapters. Here you replace that hand-written contract with generated code.
What Pigeon does
Pigeon is a code generator maintained by the Flutter team. You describe your messaging API once, in a Dart file. Pigeon then writes the matching code for Dart, Kotlin, Swift, and other targets.
Pigeon is not a different transport. The generated code still sends messages over platform channels, using the standard message codec. What changes is that you no longer write the following by hand:
- channel names
- method name strings
- argument packing and unpacking
- casts from
Object?to real types
If the two sides drift apart, you get a compile error instead of a runtime MissingPluginException or a failed cast.
| Concern | Hand-written `MethodChannel` | Pigeon |
|---|---|---|
| Channel and method names | Duplicated strings on each side | Generated from one definition |
| Argument types | `Object?`, cast manually | Typed parameters and data classes |
| Mismatch detection | At runtime | At compile time, after regeneration |
| Extra build step | None | Run the generator after each change |
| Data shapes | Maps and lists you document yourself | Generated classes with fields |
The two directions of a Pigeon API
Pigeon has two kinds of API, named by who implements them:
- A
@HostApi()is implemented by native code and called from Dart. Dart gets a generated client class. Native code gets an interface to implement. This replaces thegetUserNamecall from the earlier example. - A
@FlutterApi()is implemented in Dart and called from native code. Native code gets a generated client class. Dart gets an abstract class to extend. Use it when the host needs to push events into Flutter, such as "the user signed out".
Setting up Pigeon in the module
Add Pigeon as a development dependency of the Flutter module. It is only needed when you generate code, not at runtime.
cd my_flutter_module
dart pub add dev:pigeon
mkdir pigeonsCreate pigeons/messages.dart. This file is input to the generator. It is not part of your app, so it lives outside lib/.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(
PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
kotlinOut:
'../android_app/app/src/main/kotlin/com/example/host/Messages.g.kt',
kotlinOptions: KotlinOptions(package: 'com.example.host'),
swiftOut: '../ios_app/Runner/Messages.g.swift',
),
)
class UserSession {
UserSession({required this.name, required this.userId});
String name;
int userId;
}
@HostApi()
abstract class SessionHostApi {
UserSession getSession();
@async
void logout();
}
@FlutterApi()
abstract class CartFlutterApi {
void onCartChanged(int itemCount);
}Adjust the output paths to where your native projects live. The paths above assume the module sits next to android_app and ios_app.
Three details matter here:
UserSessionis a plain data class. Pigeon generates a matching class in each language, with the same fields.getSessionhas no annotation, so the native side must answer synchronously. It returns on the platform thread.@asynconlogoutmakes the native side finish later, through a callback. Use it for work that takes time, such as network or disk access.
Run the generator from the module directory:
dart run pigeon --input pigeons/messages.dartPigeon writes three files: messages.g.dart, Messages.g.kt, and Messages.g.swift. Commit them. Other developers and CI then build the project without needing to run the generator.
Using the generated code from Dart
The generated SessionHostApi class replaces the MethodChannel field and the string method name. Update the greeting page from the module chapter:
import 'package:flutter/material.dart';
import 'messages.g.dart';
class GreetingPage extends StatefulWidget {
const GreetingPage({super.key});
@override
State<GreetingPage> createState() => _GreetingPageState();
}
class _GreetingPageState extends State<GreetingPage> {
final _api = SessionHostApi();
String _name = '...';
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final session = await _api.getSession();
if (mounted) setState(() => _name = session.name);
}
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('Hello, $_name')));
}
}getSession() returns Future<UserSession>, so there is no invokeMethod<String> and no ?? 'guest' fallback. The compiler knows name is a String because the Pigeon definition said so.
To receive host-to-Dart calls, extend the generated CartFlutterApi and register it with setUp:
import 'package:flutter/foundation.dart';
import 'messages.g.dart';
class CartListener extends CartFlutterApi {
final ValueNotifier<int> itemCount = ValueNotifier<int>(0);
@override
void onCartChanged(int itemCount) {
this.itemCount.value = itemCount;
}
}
void registerCartListener(CartListener listener) {
CartFlutterApi.setUp(listener);
}Call registerCartListener before the host can send events, for example at the top of your entrypoint's main before runApp.
Implementing the host side on Android
Implement the generated interface in Kotlin and register it on the cached engine's messenger. This replaces the setMethodCallHandler block from the earlier chapter.
import io.flutter.embedding.engine.FlutterEngine
class SessionApiImpl : SessionHostApi {
override fun getSession(): UserSession =
UserSession(name = "Ada", userId = 42L)
override fun logout(callback: (Result<Unit>) -> Unit) {
// Clear tokens, then report completion.
callback(Result.success(Unit))
}
}
fun registerHostApis(engine: FlutterEngine) {
SessionHostApi.setUp(engine.dartExecutor.binaryMessenger, SessionApiImpl())
}Dart int becomes Kotlin Long, which is why the user ID is written 42L. To call into Dart from Kotlin, create the generated CartFlutterApi client with the same messenger and call onCartChanged.
Implementing the host side on iOS
The Swift version has the same shape. Register the handler on the engine your FlutterDependencies class owns.
import Flutter
final class SessionApiImpl: SessionHostApi {
func getSession() throws -> UserSession {
UserSession(name: "Ada", userId: 42)
}
func logout(completion: @escaping (Result<Void, Error>) -> Void) {
// Clear tokens, then report completion.
completion(.success(()))
}
}
func registerHostApis(engine: FlutterEngine) {
SessionHostApiSetup.setUp(
binaryMessenger: engine.binaryMessenger,
api: SessionApiImpl()
)
}Add Messages.g.swift to the Xcode target. A file that exists on disk but is not in the target causes "cannot find type in scope" errors.
Supported types and design rules
Pigeon sends data through the standard message codec, so it supports a limited set of types:
bool,int,double, andStringUint8List,Int32List,Int64List, andFloat64ListListandMap- your own data classes and enums
- nullable versions of the above
You cannot send arbitrary objects, callbacks, or streams. Keep these rules in mind when you design the API:
- Send data, not behavior. Return a
UserSessioninstead of exposing an object with methods. - Keep messages small. Each call is encoded and copied between the Dart and native sides.
- Use enums for fixed choices instead of strings.
- Mark fields nullable only when they can be missing. Pigeon enforces the difference on both sides.
- Prefer
@asyncfor anything that touches I/O, so the platform thread stays free.
Pigeon and multiple engines
If you later run several engines with FlutterEngineGroup, each engine needs its own registration. Call setUp once per engine, using that engine's messenger. A single global registration reaches only one engine. Pigeon's messageChannelSuffix option lets you keep several instances of the same API apart on one messenger.
Common errors
- Channel error: "Unable to establish connection on channel". The native
setUpcall did not run before Dart called the API. Register handlers right after creating the engine and before launching the screen. - Native code does not compile after a Dart change. The generated interface changed. Rerun the generator, then update your implementations.
- Handlers stop working. If you create a new engine, such as after destroying a cached one, register the APIs on it again.
- Generator fails on an unsupported type. Replace the type with one from the supported list, or wrap it in a data class.
- Stale generated files in CI. Check in the
.gfiles, or run the generator as a CI step and fail the build ifgit diffshows changes.
Exercise
You add a new method int getCartCount(); to SessionHostApi in pigeons/messages.dart. List the steps you must take before the app compiles and runs, and say which step the compiler enforces for you.
Show answer
First, rerun dart run pigeon --input pigeons/messages.dart to regenerate the Dart, Kotlin, and Swift files. Second, implement getCartCount in the Kotlin SessionApiImpl (returning a Long) and in the Swift SessionApiImpl. Third, call SessionHostApi().getCartCount() from Dart if needed. The compiler enforces the second step: the new interface method has no implementation in the native classes, so both native builds fail until you add it. With a hand-written MethodChannel this mistake would only appear at runtime.
Exercise
The host app needs to tell Flutter whenever the user signs out. Which Pigeon annotation do you use, who implements the API, and who calls it?
Show answer
Use @FlutterApi(). The Dart side implements it by extending the generated abstract class and registering it with setUp. The native side calls it through the generated client class, created with the engine's binary messenger.