Sub topic 13
Plugins and Pigeon: going beyond hand-written channels
This chapter assumes you have written a MethodChannel and an EventChannel by hand. You should know the standard codec's type mappings and the PlatformException and MissingPluginException error paths. It covers two tools that remove most of the repetition: plugin packaging and Pigeon code generation.
Where hand-written channels start to hurt
The battery example from earlier chapters needs three things to agree: a channel name string, method name strings, and the shape of the arguments and results. Nothing checks them. A typo in 'getBatteryLevl' compiles on all three sides and fails at runtime with notImplemented, which Dart reports as MissingPluginException. A map argument with a misspelled key arrives as null on the native side.
Two problems grow as the app does:
- Stringly typed contracts. Every call site and handler has to cast
Object?values by hand. Nothing tells you when one side changes. - Code trapped in one app. Handlers written in
MainActivityorAppDelegatecan't be reused in a second app or shared with other developers.
Plugins solve the second problem. Pigeon solves the first. They are independent, and most real projects use both.
Plugins: packaging channel code
A Flutter plugin is a Dart package that also contains native code. The Dart code owns the channel. The Android and iOS code registers its handlers when the Flutter engine starts, so the app's MainActivity and AppDelegate stay untouched.
Create one with the plugin template:
flutter create --template=plugin --platforms=android,ios \
-a kotlin -i swift --org com.example batteryThe generated pubspec.yaml declares which class registers on each platform:
flutter:
plugin:
platforms:
android:
package: com.example.battery
pluginClass: BatteryPlugin
ios:
pluginClass: BatteryPluginFlutter's build tooling reads this block and generates GeneratedPluginRegistrant. That is the class the iOS example in an earlier chapter called with GeneratedPluginRegistrant.register(with: self).
Android plugin lifecycle
On Android the plugin implements FlutterPlugin. You create the channel in onAttachedToEngine and remove the handler in onDetachedFromEngine:
package com.example.battery
import android.content.Context
import android.os.BatteryManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
class BatteryPlugin : FlutterPlugin, MethodCallHandler {
private lateinit var channel: MethodChannel
private lateinit var context: Context
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
channel = MethodChannel(binding.binaryMessenger, "com.example.battery/battery")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"getBatteryLevel" -> {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level >= 0) result.success(level)
else result.error("UNAVAILABLE", "Battery level not available.", null)
}
else -> result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}A plugin has no Activity by default. It gets an application Context from the binding. If you need an Activity (to show a permission dialog, for example), also implement ActivityAware and handle the attach and detach callbacks. The activity can be replaced while the engine stays alive, so never store it in a long-lived field without clearing it.
Plugin layouts
| Layout | Structure | Use it when |
|---|---|---|
| App-local code | Handlers in `MainActivity` and `AppDelegate` | One app, one or two calls |
| Single plugin package | One package with Dart, Android, and iOS code | Reuse across your own apps |
| Federated plugin | An app-facing package, a platform interface package, and one package per platform | Several teams or third parties implement platforms, or you add web or desktop later |
In a federated plugin, the platform interface package defines an abstract class. The app-facing package forwards calls to whichever implementation is registered. Each platform package registers itself as the default for its platform. This is why you add url_launcher once and the right implementation is chosen for you.
Pigeon: generating the contract
Pigeon is a code generator from the Flutter team (package:pigeon). You describe your API once in a Dart file. Pigeon writes the Dart, Kotlin, and Swift code for the channel, including the codec, the argument packing, and the casts. The channel names and method names are generated, so they can't drift apart.
Add it as a dev dependency:
dev_dependencies:
pigeon: ^22.0.0Write the definition in a file outside lib/, conventionally pigeons/messages.dart:
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
kotlinOut: 'android/src/main/kotlin/com/example/battery/Messages.g.kt',
kotlinOptions: KotlinOptions(package: 'com.example.battery'),
swiftOut: 'ios/Classes/Messages.g.swift',
))
enum ChargeState { unknown, charging, discharging, full }
class BatteryInfo {
BatteryInfo({required this.level, required this.state});
int level;
ChargeState state;
}
@HostApi()
abstract class BatteryApi {
BatteryInfo getBatteryInfo();
}Run the generator:
dart run pigeon --input pigeons/messages.dartYou commit the generated *.g.* files. Don't edit them. Each run overwrites them.
What Pigeon generates
- Dart: a class
BatteryApiwhosegetBatteryInfo()returnsFuture<BatteryInfo>. Dart callers see ordinary typed async methods. - Kotlin: an interface
BatteryApiwithfun getBatteryInfo(): BatteryInfo, plusBatteryApi.setUp(binaryMessenger, api)to register your implementation. - Swift: a protocol
BatteryApiwithfunc getBatteryInfo() throws -> BatteryInfo, plusBatteryApiSetup.setUp(binaryMessenger:api:).
You implement the interface and register it. Here is the Kotlin side:
package com.example.battery
import android.content.Context
import android.os.BatteryManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
class BatteryPlugin : FlutterPlugin, BatteryApi {
private lateinit var context: Context
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
BatteryApi.setUp(binding.binaryMessenger, this)
}
override fun getBatteryInfo(): BatteryInfo {
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) ChargeState.CHARGING else ChargeState.DISCHARGING
return BatteryInfo(level.toLong(), state)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
BatteryApi.setUp(binding.binaryMessenger, null)
}
}Two details matter here. Pigeon maps Dart int to Kotlin Long and Swift Int64, which is why the level is converted with toLong(). And FlutterError is a generated class. Throwing it reaches Dart as a PlatformException with the same code, message, and details, so the error handling you learned for hand-written channels still applies.
The Dart caller is short:
import 'src/messages.g.dart';
Future<void> main() async {
final api = BatteryApi();
final info = await api.getBatteryInfo();
print('${info.level}% (${info.state.name})');
}Other Pigeon features
@asyncon a host method makes the native implementation take a completion callback instead of returning a value. Use it for work that must not block the platform thread.@FlutterApi()defines the reverse direction: native code calls Dart. You implement the generated abstract class in Dart and callsetUp. Use it for callbacks such as "download finished".- Data classes and enums are encoded by a generated codec, so you can pass them without writing a
StandardMessageCodecsubclass. - Test output. Setting
dartTestOutgenerates a test harness. It lets you mock a host API in Dart tests without callingsetMockMethodCallHandlerand without hard-coding method names. - Streams. Recent Pigeon versions can generate EventChannel code with
@EventChannelApi. Check the changelog for your version before relying on it.
Pigeon limits
Pigeon has restrictions you should know before adopting it.
- Collections are limited to
ListandMap, and their element types must be nullable (List<String?>, notList<String>). - Classes can't extend other classes, and fields can only hold supported types.
- Method arguments can't have default values.
- The generated code ties your native code to the Pigeon version that produced it. Regenerate all languages together, in one commit.
Choosing the approach
| Need | Choice |
|---|---|
| One simple call in one app | Hand-written MethodChannel |
| A stream of native events | EventChannel (or `@EventChannelApi` if your Pigeon version supports it) |
| Many methods, structured data, or two or more developers | Pigeon |
| Reuse across apps, or publishing | Plugin package |
| Several platforms with different owners | Federated plugin |
Common mistakes
- Registering the plugin in the app instead of the plugin. If you leave
pluginClassout ofpubspec.yaml, the handler is never registered. Calls fail withMissingPluginException, and it usually only happens after a full rebuild, not a hot reload. - Forgetting to tear down. Not clearing the handler in
onDetachedFromEnginecan leave a handler that holds a staleContext. This matters with multiple engines or background isolates. - Hand-editing
*.g.*files. The next generator run silently discards your change. - Choosing a federated layout too early. The extra packages add publishing and versioning work. Use one plugin package until a second platform owner appears.
Exercise
You add a new field temperature to the BatteryInfo class in pigeons/messages.dart and regenerate only the Dart output. The Android build still uses the old generated Kotlin file. What happens at runtime, and what should you have done instead?
Show answer
The Dart and Kotlin codecs now disagree about the shape of BatteryInfo. The call can fail with a cast or index error, or the native side can send a list that Dart decodes with a missing or null field. No compile error warns you. You should rerun dart run pigeon --input pigeons/messages.dart so that the Dart, Kotlin, and Swift outputs are all regenerated, update the Kotlin and Swift implementations to fill in temperature, and commit all of the files together.
Exercise
Your team wants the same battery API on Android, iOS, and later web, with the web code written by a different team. Which plugin layout fits, and which package defines the abstract class that every platform implements?
Show answer
A federated plugin fits. The platform interface package (for example battery_platform_interface) defines the abstract class. The app-facing package forwards calls to it, and each platform package (battery_android, battery_ios, battery_web) implements it and registers itself as the default for its platform.