Sub topic 6
Implementing the API in Kotlin and Swift
This chapter assumes you have already generated Messages.g.kt and Messages.g.swift from the BatteryApi schema in the earlier chapters. You should be able to read basic Kotlin and Swift, and know that an Android app starts from a FlutterActivity and an iOS app from an AppDelegate. The chapter shows how to write the native classes that answer Dart's calls, and how to register them so the calls arrive.
What the generator gives you to implement
For each @HostApi() class, Pigeon writes a native contract and a registration function. The contract is where you work. You write one class per platform that fills in the contract, and the generated code handles decoding arguments, calling your method, and encoding the result.
| Piece | Kotlin | Swift |
|---|---|---|
| Contract you implement | `interface BatteryApi` | `protocol BatteryApi` |
| Data class | `data class BatteryInfo` | `struct BatteryInfo` |
| Enum | `enum class BatteryState` (values such as `UNKNOWN`) | `enum BatteryState` (values such as `.unknown`) |
| Registration | `BatteryApi.setUp(binaryMessenger, api)` | `BatteryApiSetup.setUp(binaryMessenger:api:)` |
The Kotlin setUp is a function on the interface's companion object. In Swift, it is a static function on a separate generated class named after the API with a Setup suffix.
Your implementation never touches a channel name or a raw Any?. If the schema changes and your class no longer matches, the native build fails. That compile error is the main benefit of Pigeon over string-based MethodChannel code.
Implementing the interface in Kotlin
Put the class in a normal Kotlin file next to the generated one. It takes whatever Android objects it needs through its constructor, which keeps it easy to reason about.
import android.content.Context
import android.os.BatteryManager
class BatteryApiImpl(private val context: Context) : BatteryApi {
override fun getBatteryInfo(): BatteryInfo {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
return BatteryInfo(level = level.toLong(), state = BatteryState.UNKNOWN)
}
}Three details matter here.
- Integer width. A Dart
intis 64 bits, so Pigeon generatesLongin Kotlin.getIntPropertyreturns anInt, so you must calltoLong(). Forgetting this is the most common first compile error. - Named arguments. The generated
BatteryInfohas the constructor parameterslevelandstate, matching the Dart field names. Renaming a field in the schema renames it here. - Return type. The method returns
BatteryInfodirectly. Because the schema declared a non-nullable return, Kotlin will not let you returnnull.
Registering it in MainActivity
Registration connects your class to the engine's binary messenger. Do this in configureFlutterEngine, which Flutter calls once the engine exists.
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
BatteryApi.setUp(
flutterEngine.dartExecutor.binaryMessenger,
BatteryApiImpl(this)
)
}
}Call super.configureFlutterEngine first so Flutter's own plugin registration runs. Then call setUp with the messenger and your instance. After this line, any BatteryApi().getBatteryInfo() call from Dart is routed to BatteryApiImpl.
Passing this as the Context is fine for an activity-scoped API. If the implementation outlives the activity, for example in a plugin, pass applicationContext instead so you do not leak the activity.
Implementing the protocol in Swift
The Swift side follows the same pattern. The protocol method is marked throws, which is how you report errors (covered in a later chapter).
import Flutter
import UIKit
class BatteryApiImpl: BatteryApi {
func getBatteryInfo() throws -> BatteryInfo {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
let level = Int64(max(device.batteryLevel, 0) * 100)
let state: BatteryState
switch device.batteryState {
case .charging: state = .charging
case .unplugged: state = .discharging
case .full: state = .full
default: state = .unknown
}
return BatteryInfo(level: level, state: state)
}
}Points to notice:
- Battery monitoring must be switched on. Until
isBatteryMonitoringEnabledistrue,batteryLevelreturns-1. Themax(..., 0)guard stops that sentinel value from becoming-100in Dart. The simulator also reports-1, so test on a device. - Int64. Swift uses
Int64for Dartint, so you convert explicitly. - Enum mapping. The generated
BatteryStateis your own type, not UIKit's. You translate between the two with aswitch. Thedefaultbranch covers.unknownand any case Apple adds later.
Registering it in AppDelegate
On iOS, you need the FlutterViewController to reach the binary messenger. In a standard app, register inside application(_:didFinishLaunchingWithOptions:).
import Flutter
import UIKit
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let controller = window?.rootViewController as! FlutterViewController
BatteryApiSetup.setUp(binaryMessenger: controller.binaryMessenger, api: BatteryApiImpl())
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}The as! cast assumes the root view controller is a FlutterViewController, which holds for the default template. If your app uses scenes or a custom root controller, the template for your Flutter version may differ. Adapt the lookup, but keep the setUp call unchanged.
Registering inside a plugin
If Pigeon lives in a Flutter plugin rather than an app, the engine's messenger comes from the plugin binding, and you should also unregister when the plugin detaches. Passing null removes the handler.
import io.flutter.embedding.engine.plugins.FlutterPlugin
class BatteryPlugin : FlutterPlugin {
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
BatteryApi.setUp(binding.binaryMessenger, BatteryApiImpl(binding.applicationContext))
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
BatteryApi.setUp(binding.binaryMessenger, null)
}
}On iOS, the equivalent is the plugin's register(with registrar: FlutterPluginRegistrar) method. Use registrar.messenger() as the messenger and pass your implementation to BatteryApiSetup.setUp.
Unregistering matters because one process can host several engines, for example with add-to-app or background isolates. A handler left on a dead engine's messenger is a leak, and a handler registered twice on the same messenger replaces the first.
Calling it from Dart
Nothing changes on the Dart side. The generated class is what you built in the previous chapter.
import 'src/messages.g.dart';
Future<void> printBattery() async {
final api = BatteryApi();
final info = await api.getBatteryInfo();
print('Battery ${info.level}% (${info.state.name})');
}Even though the native method looks synchronous, the Dart call returns a Future. The message crosses the engine boundary asynchronously regardless of how the native method is written.
Common mistakes
- Registering too late. If Dart calls the API before
setUpruns, the call fails with achannel-errorPlatformException. Registering inconfigureFlutterEngineordidFinishLaunchingWithOptionsavoids this. A call from a background isolate or a second engine needs asetUpon that engine too. - Editing generated files. Changes to
Messages.g.ktorMessages.g.swiftare overwritten on the next run. Put logic in your ownBatteryApiImplclasses. - Package mismatch on Android. The
packageinKotlinOptionsmust match the package of the file's directory. If it does not, you get unresolved references inMainActivity. Match thepackageoption to your directory structure, or import the generated names explicitly. - Blocking the main thread. Pigeon runs host methods on the platform's main thread by default. A slow call in
getBatteryInfofreezes the UI. Moving work off the main thread is the topic of the async chapter. - Wrong cast of the root view controller. On iOS,
as!crashes if the window's root is not aFlutterViewController. Check your app's launch setup if you see this at startup.
Exercise
A teammate adds String? chargerType to the Dart BatteryInfo class and regenerates. The Kotlin and Swift builds now fail inside BatteryApiImpl. Why does this happen, and what do you change in each implementation?
Show answer
The generated BatteryInfo now has a chargerType field, so the existing constructor calls in BatteryApiImpl no longer match. This is the compile-time check Pigeon provides. In Kotlin, a nullable field is String?, so pass chargerType = null or a real value as a named argument. In Swift, the generated initializer takes chargerType: String?, so add chargerType: nil or a real value. Update both implementations, then rebuild.
Exercise
On iOS, your app shows a battery level of 0 on a real device. batteryLevel is correct in other apps. What is the likely cause in BatteryApiImpl.getBatteryInfo, and how do you fix it?
Show answer
UIDevice.current.isBatteryMonitoringEnabled was not set to true before reading batteryLevel, so UIKit returns -1, and max(-1, 0) * 100 becomes 0. Set isBatteryMonitoringEnabled = true before reading the level, as the example does.
Exercise
Why does a plugin call BatteryApi.setUp(binding.binaryMessenger, null) in onDetachedFromEngine?
Show answer
Passing null removes the handler from that engine's messenger. Without it, the handler and its captured context stay registered after the engine detaches, which can leak memory. It also prevents confusion if the engine is later reused with a new implementation.