Sub topic 7
Calling Dart from Native with a FlutterApi
This chapter assumes that you know basic Dart and Flutter app structure, can use async and await, and can read Kotlin or Swift. It also assumes that you have generated Pigeon code and understand that Flutter and native code communicate through platform channels.
A HostApi lets Dart call native code. A FlutterApi reverses that direction: native code calls a Dart implementation through generated, typed methods. This is useful for native callbacks, such as battery changes, location updates, or a completed system operation.
Declare the FlutterApi
Define the callback in the same Pigeon input file as your other messages and APIs:
@FlutterApi()
abstract class BatteryEvents {
void onBatteryChanged(BatteryInfo info);
}Pigeon generates matching code for Dart and each configured native platform. The generated Dart class is abstract, so your application provides the implementation.
The generated method usually returns a Future on the native side because the call crosses a process boundary inside the application. Even when the Dart method itself returns void, native code must normally provide a result callback.
Implement and register it in Dart
Create a concrete Dart class and register it with the generated setUp method:
import 'src/messages.g.dart';
class BatteryListener extends BatteryEvents {
@override
void onBatteryChanged(BatteryInfo info) {
print('Battery changed: ${info.level}%');
}
}
void registerBatteryEvents() {
BatteryEvents.setUp(BatteryListener());
}Call registerBatteryEvents during application or plugin setup, before native code can send an event. Registration installs a message handler on Flutter’s binary messenger. Without registration, native calls have no Dart object to receive them.
For a Flutter application, registration can happen before runApp:
void main() {
registerBatteryEvents();
runApp(const MyApp());
}For a plugin, register the handler when the plugin attaches to the Flutter engine. Avoid registering repeatedly without removing or replacing the previous handler, because the latest registration can replace the earlier one.
sequenceDiagram
participant N as Native code
participant M as Binary messenger
participant D as Dart BatteryListener
N->>M: onBatteryChanged(BatteryInfo)
M->>D: Deliver typed message
D->>D: Run onBatteryChanged
D-->>M: Return success or error
M-->>N: Invoke result callbackCall the FlutterApi from native code
Pigeon generates a native client for the FlutterApi. Kotlin can use that client to send a typed BatteryInfo object to Dart:
import io.flutter.embedding.engine.FlutterEngine
class BatteryNotifier(flutterEngine: FlutterEngine) {
private val events =
BatteryEvents(flutterEngine.dartExecutor.binaryMessenger)
fun publish(level: Long, state: BatteryState) {
val info = BatteryInfo(level = level, state = state)
events.onBatteryChanged(info) { error ->
if (error != null) {
println("Dart rejected battery event: ${error.message}")
}
}
}
}The exact generated constructor and callback type depend on the Pigeon version and generator options. Use the generated source as the authority when connecting the client. Do not recreate the message channel manually.
Swift uses the generated client in the same way:
let events = BatteryEvents(binaryMessenger: controller.binaryMessenger)
events.onBatteryChanged(
BatteryInfo(level: 84, state: .charging)
) { error in
if let error = error {
print("Dart rejected battery event: \(error.localizedDescription)")
}
}The native client should use the messenger belonging to the Flutter engine that hosts the Dart code. Using a messenger from another engine sends the message to the wrong isolate or to no listener.
Choose FlutterApi or an event channel
Use a FlutterApi when events have a defined schema and a small number of operations. Pigeon gives each event typed arguments and generated error handling.
| Design | Best fit | Main trade-off |
|---|---|---|
| FlutterApi | Typed native-to-Dart callbacks | Requires generated code and lifecycle coordination |
| EventChannel | A stream of loosely coupled events | Payloads and event names need manual conventions |
For a high-frequency stream, consider batching events or using an EventChannel. A FlutterApi call still crosses the platform boundary for every event.
Exercise
What must happen before native code calls a generated FlutterApi method, and why?
Show answer
Dart must register an implementation with the generated setUp method. Registration installs the binary-messenger handler that receives and dispatches native calls; without it, the call cannot reach a Dart object.