Sub topic 2
Declaring a HostApi and calling it from Dart
This chapter assumes you have a Flutter app with a working Dart and Pigeon setup from the previous chapter, and that you can read Kotlin and Swift. A HostApi is an abstract Dart class that Pigeon turns into a typed call from Dart to native code.
Declaring a HostApi
Add the HostApi to the same schema file you used for the data types. The @HostApi() annotation tells Pigeon to generate a Dart client and a native interface.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
kotlinOut: 'android/app/src/main/kotlin/com/example/app/Messages.g.kt',
kotlinOptions: KotlinOptions(package: 'com.example.app'),
swiftOut: 'ios/Runner/Messages.g.swift',
))
class BatteryInfo {
BatteryInfo({required this.level});
int level;
}
@HostApi()
abstract class BatteryApi {
BatteryInfo getBatteryInfo();
}Run dart run pigeon --input pigeons/messages.dart to generate the files. Then call the API from Dart:
import 'src/messages.g.dart';
Future<void> printBattery() async {
final info = await BatteryApi().getBatteryInfo();
print('Battery ${info.level}%');
}Implementing the API in Kotlin and Swift
Pigeon generates a Kotlin interface and a Swift protocol named BatteryApi. Your native class implements it. On Android, Dart int maps to Kotlin Long, so the code converts the value.
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())
}
}Register the implementation in MainActivity:
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))
}
}On iOS, the Swift class conforms to the generated protocol. Register it with the generated BatteryApiSetup.setUp call once the Flutter view controller exists.
import Flutter
import UIKit
class BatteryApiImpl: BatteryApi {
func getBatteryInfo() throws -> BatteryInfo {
UIDevice.current.isBatteryMonitoringEnabled = true
let level = Int64(max(UIDevice.current.batteryLevel, 0) * 100)
return BatteryInfo(level: level)
}
}Calling Dart from native with a FlutterApi
A FlutterApi reverses the direction. Declare it with @FlutterApi(), and native code calls the generated client to send a message to Dart. Dart implements the abstract class and registers it with setUp.
@FlutterApi()
abstract class BatteryEvents {
void onBatteryChanged(BatteryInfo info);
}Async methods and threading
Mark a HostApi method with @async when the native work takes time. Kotlin then returns the result through a callback, and Swift uses a completion handler. Pigeon delivers the call on the platform's main thread, so move slow work such as disk or network access to a background thread and call back when it finishes. Exceptions thrown on the native side reach Dart as PlatformException.
sequenceDiagram
Dart->>Native: getBatteryInfo()
Native-->>Dart: BatteryInfo(level)Exercise
Why does the Kotlin code call level.toLong()?
Show answer
Pigeon maps Dart int to Kotlin Long, so the generated BatteryInfo expects a Long value.