Sub topic 5
Declaring a HostApi and Calling It from Dart
Assume you know basic Dart and Flutter app structure, can use async and await, and understand that Flutter communicates with Android and iOS through platform channels. This chapter also assumes that Pigeon is configured and its generator has produced messages.g.dart.
What a HostApi does
A HostApi describes methods that Dart can call on the host platform. The host platform means Android or iOS code running outside the Dart environment.
Without Pigeon, Dart usually sends a method name and loosely typed arguments through a MethodChannel:
final result = await channel.invokeMethod('getBatteryInfo');This code can fail because the method name, argument names, and returned value are only agreed on by convention. A typo is not detected when Dart code is compiled. You may also need casts when reading the result.
A Pigeon HostApi defines the contract once. Pigeon then generates a Dart client and matching native interfaces. The Dart client has typed methods, and each method returns a Future when the call crosses into native code.
flowchart LR
D[Dart code] --> C[Generated Dart HostApi client]
C --> M[Binary messenger]
M --> N[Generated native interface]
N --> I[Native implementation]
I --> R[Typed result or error]
R --> DDeclare the API
Put the declaration in the Pigeon input file. The @HostApi() annotation tells Pigeon that Dart will call the generated native implementation.
// pigeons/messages.dart
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',
))
enum BatteryState { charging, discharging, full, unknown }
class BatteryInfo {
BatteryInfo({required this.level, required this.state});
int level;
BatteryState state;
}
@HostApi()
abstract class BatteryApi {
BatteryInfo getBatteryInfo();
}BatteryInfo is a data class in the schema. It groups the battery percentage and state into one typed result. BatteryApi is an abstract class because the native side will provide its implementation.
The method is synchronous in the schema, but the generated Dart method is asynchronous across the platform boundary. In application code, use await:
import 'src/messages.g.dart';
Future<void> printBattery() async {
final api = BatteryApi();
final info = await api.getBatteryInfo();
print('Battery ${info.level}% (${info.state.name})');
}The generated client encodes the method call, sends it through Flutter's binary messenger, waits for the native response, and decodes that response as BatteryInfo. Your Dart code does not need a channel name, a manual map conversion, or a cast.
Match the generated contract
Every side must use the same generated contract. The native implementation must return the fields and types declared by BatteryInfo. If native code returns an invalid value, the generated codec can report an error while decoding it.
| Schema declaration | Dart result | Native result |
|---|---|---|
| `int level` | `int` | Kotlin `Long` or Swift integer type |
| `BatteryState state` | `BatteryState` | Generated enum |
| `BatteryInfo getBatteryInfo()` | `Future<BatteryInfo>` | Generated interface method |
Regenerate the files whenever the schema changes:
dart run pigeon --input pigeons/messages.dartDo not edit messages.g.dart or other generated files by hand. A later generation would overwrite those edits.
Calling methods safely
Treat a HostApi call like any other asynchronous operation. Handle expected failures at the application boundary:
Future<BatteryInfo?> readBattery() async {
try {
return await BatteryApi().getBatteryInfo();
} on PlatformException catch (error) {
print('Could not read battery: ${error.message}');
return null;
}
}Import package:flutter/services.dart when catching PlatformException. Keep platform-specific recovery near the service layer, so widgets receive a useful result instead of knowing about channel details.
Exercise
Why does BatteryApi().getBatteryInfo() return a Future<BatteryInfo> in Dart even though the schema method has no Future keyword?
Show answer
The call crosses the platform boundary through the binary messenger, so the generated Dart client must wait asynchronously for the native response.