Sub topic 5
Declaring a HostApi and calling it from Dart
A HostApi is the part of a Pigeon schema that describes calls going from Dart to native code. This chapter covers how to declare one, what Pigeon generates from it, and how to call it from Dart. Native implementations come in the next chapter.
Prerequisites
This chapter assumes you have:
- Pigeon added as a dev dependency and the generator command working (see the setup chapter).
- A schema with data classes and enums (see the schema chapter).
- Comfort with
async/awaitandFuturein Dart. - A rough idea of what a
MethodChanneldoes.
What a HostApi is
In Pigeon, the "host" is the platform side of the app: Android or iOS. A HostApi declares methods that Dart calls and that the host implements. Dart is the caller, and Kotlin or Swift is the implementer.
You write the declaration as an abstract class annotated with @HostApi(). Pigeon reads it and produces three things:
- A Dart class with the same name. It has one method per declaration and sends the message over a channel.
- A Kotlin interface to implement, plus a
setUpfunction that registers your implementation. - A Swift protocol to conform to, plus a matching setup function.
The channel names, argument packing and casts live inside the generated files. Your app code never sees a string like "getBatteryInfo".
Declaring the API
The declaration lives in the same input file as your data classes. Here is the schema from earlier chapters, with the HostApi at the bottom:
// 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();
}The declaration has these parts:
@HostApi()marks the class as Dart-to-native.- The class is
abstract. You never write a body, because Pigeon generates the real code. - Each method is a signature only. Its parameter types and return type become the typed contract on every platform.
- The method name becomes the method name in Dart, Kotlin and Swift.
Run the generator after every change to this file:
dart run pigeon --input pigeons/messages.dartMethod shapes
A HostApi method can take positional parameters, return a value, return nothing, or return a nullable value. These all work:
@HostApi()
abstract class SettingsApi {
// No arguments, returns a value.
String getLocaleTag();
// One argument, returns nothing.
void setBrightness(double value);
// Several arguments, nullable return.
String? readPreference(String key, String? fallback);
// Takes and returns a data class.
BatteryInfo refresh(BatteryInfo previous);
}Some details to keep in mind:
- Nullability is part of the contract. A
String?return means the native side may returnnull, and the generated Dart method returnsFuture<String?>. A non-nullable return is a promise that native code must keep. - Parameters are positional. If a call needs many values, group them in a data class. That keeps call sites readable and lets you add a field later without changing the method signature.
- A
voidmethod still returns aFuture<void>on the Dart side. You can await it to know that native code finished or to catch its error.
Why every call is async in Dart
Dart never blocks on a platform call. The message crosses from the Dart isolate to the platform thread, native code runs, and a reply comes back later. So every generated Dart method returns a Future, even for something that feels instant like getLocaleTag().
This is a property of the channel, not of your declaration. Marking a native method as asynchronous (covered in the threading chapter) changes how native code replies. It does not change the Dart side, which was always a Future.
Calling the generated class from Dart
The generated Dart class has the same name as your abstract class. You create it and call its methods:
import 'src/messages.g.dart';
Future<void> printBattery() async {
final api = BatteryApi();
final info = await api.getBatteryInfo();
print('Battery ${info.level}% (${info.state.name})');
}Compare this with the hand-written equivalent:
import 'package:flutter/services.dart';
Future<void> printBatteryUntyped() async {
const channel = MethodChannel('com.example.app/battery');
final result = await channel.invokeMethod<Map<Object?, Object?>>('getBatteryInfo');
final level = result?['level'] as int?;
final state = result?['state'] as String?;
print('Battery $level% ($state)');
}The second version has a channel name, a method name, a map key and two casts, and none of them is checked at compile time. A typo in any string fails at runtime. The Pigeon version fails to compile if you misspell getBatteryInfo or read a field that does not exist.
Wrapping the generated class
The generated class is easy to call directly, but it is also a concrete class. If widgets and services create BatteryApi() themselves, they are hard to test and hard to swap out. A common approach is to take the API as a constructor parameter and give it a default:
import 'src/messages.g.dart';
class BatteryRepository {
BatteryRepository({BatteryApi? api}) : _api = api ?? BatteryApi();
final BatteryApi _api;
Future<String> describe() async {
final info = await _api.getBatteryInfo();
return '${info.level}% ${info.state.name}';
}
}The testing chapter builds on this. For now, notice that the rest of the app depends on BatteryRepository and never on channels.
Binary messenger and multiple engines
The generated constructor takes an optional binaryMessenger parameter:
final api = BatteryApi(binaryMessenger: myMessenger);If you leave it out, Pigeon uses the default messenger of the running Flutter engine. That is correct for most apps. You pass one explicitly when code runs in a background isolate or a second engine, where the default messenger is not the one you want.
The generated class also has an optional messageChannelSuffix parameter in current Pigeon versions. It lets you register several implementations of the same API on different channels, for example one per plugin instance. The native setUp call must use the same suffix. Check the generated file in your project for the exact signature, since it depends on your Pigeon version.
What happens when native code is missing
If Dart calls a HostApi method before native code has called setUp, or on a platform where you never wrote an implementation, the call does not return a result. The generated Dart code throws a PlatformException with the code channel-error, and the message says it could not establish a connection on the channel.
import 'package:flutter/services.dart';
import 'src/messages.g.dart';
Future<void> safeCall() async {
try {
final info = await BatteryApi().getBatteryInfo();
print(info.level);
} on PlatformException catch (e) {
print('Native call failed: ${e.code} ${e.message}');
}
}This is the most common first-run error. Check these causes in order:
setUpis never called, or runs after Dart already made the call.- The Kotlin or Swift
setUpis registered on the wrong messenger. - The generated files are out of date and the channel names or suffixes do not match.
- You are running on a platform, such as web or desktop, for which you did not generate or register an implementation.
Design guidelines for HostApi methods
Pigeon makes it cheap to add methods, so APIs tend to grow. A few rules keep them manageable:
- Name methods after intent.
getBatteryInfosays what the caller gets.doBatteryThingdoes not. - Prefer one call with a data class over several small calls. Every call crosses the boundary and has a cost. Two separate calls for level and state can also return values from different moments.
- Keep the API small. Each method needs a native implementation on every platform. Expose what Dart needs, not everything the platform offers.
- Split by feature. Several small
HostApiclasses (BatteryApi,SettingsApi) are easier to implement and test than one large one. - Make nullability honest. Use
?for values that can be absent, so native code is not forced to invent a placeholder.
Quick reference
| Declaration | Generated Dart signature | Meaning |
|---|---|---|
| `void ping();` | `Future<void> ping()` | No result, completes when native code finishes |
| `String name();` | `Future<String> name()` | Native must return a non-null string |
| `String? name();` | `Future<String?> name()` | Native may return `null` |
| `BatteryInfo get(int id);` | `Future<BatteryInfo> get(int id)` | Typed argument and typed result |
| `void set(BatteryInfo info);` | `Future<void> set(BatteryInfo info)` | Sends a data class to native code |
Summary of the workflow
- Add an abstract class annotated with
@HostApi()to the Pigeon input file. - Declare each method as a signature using supported types.
- Run
dart run pigeon --input pigeons/messages.dart. - Call the generated Dart class from a repository or service, not directly from widgets.
- Implement and register the native side, which is the next chapter's topic.
Exercise
A teammate declares int getLevel(); in a HostApi and calls final level = BatteryApi().getLevel(); in Dart, then uses level + 1. The code does not compile. What is wrong, and what is the fix? Then, on a device where the native setUp was never called, what happens when the corrected call runs?
Show answer
Every generated Dart HostApi method returns a Future, so getLevel() returns Future<int>, and Future<int> + 1 is a type error. The fix is to make the caller async and await the result: final level = await BatteryApi().getLevel();. If native setUp was never called, the call throws a PlatformException with the code channel-error, so wrap the call in try/catch or make sure the native side registers the implementation before Dart calls it.
Exercise
You need Dart to ask native code for a user's preferred name, which may not be set, and to send a new name back to native code. Write the HostApi declaration, and state the Dart return types Pigeon generates.
Show answer
@HostApi()
abstract class ProfileApi {
String? getPreferredName();
void setPreferredName(String name);
}
The generated Dart methods are Future<String?> getPreferredName() and Future<void> setPreferredName(String name). The ? makes the possibly absent name explicit, and void still yields a Future<void> that you can await.