Sub topic 7
Calling Dart from native with a FlutterApi
This chapter assumes you have a working HostApi from the earlier chapters. That means a pigeons/messages.dart input file, generated code, and a native implementation registered on Android and iOS. You should also be comfortable with Dart Futures and with reading Kotlin and Swift.
A HostApi lets Dart call native code. Some events start on the native side: a battery level change, a push token refresh, or a deep link arriving. For these cases Pigeon provides the @FlutterApi() annotation, which reverses the direction of the call.
What a FlutterApi generates
You declare a FlutterApi as an abstract class in the same input file as your HostApi. Pigeon then generates different code on each side:
| Side | What Pigeon generates | Who writes the logic |
|---|---|---|
| Dart | An abstract class with a static `setUp` method | You extend the class and implement the methods |
| Kotlin | A class that takes a `BinaryMessenger` and has one method per API method | Nobody; you call it |
| Swift | A class that takes a `FlutterBinaryMessenger` and has one method per API method | Nobody; you call it |
This is the mirror image of a HostApi. With a HostApi, native code implements an interface and Dart gets a client. With a FlutterApi, Dart implements the abstract class and native code gets a client.
Declaring the FlutterApi
Add the FlutterApi to the same pigeons/messages.dart file that holds BatteryApi. It reuses the BatteryInfo and BatteryState types you already defined.
@FlutterApi()
abstract class BatteryEvents {
void onBatteryChanged(BatteryInfo info);
}Run the generator again:
dart run pigeon --input pigeons/messages.dartAll three output files are rewritten. Your existing HostApi code is unaffected unless you changed its declaration.
Implementing the Dart side
Extend the generated abstract class and override each method. Then register the instance with the generated static setUp.
import 'package:flutter/widgets.dart';
import 'src/messages.g.dart';
class BatteryListener extends BatteryEvents {
BatteryListener(this.onChanged);
final void Function(BatteryInfo info) onChanged;
@override
void onBatteryChanged(BatteryInfo info) {
onChanged(info);
}
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
BatteryEvents.setUp(
BatteryListener((info) => debugPrint('Battery: ${info.level}%')),
);
runApp(const Placeholder());
}Three points about this code:
WidgetsFlutterBinding.ensureInitialized()comes first.setUpneeds the default binary messenger, which exists only after the binding is initialized.setUpregisters a message handler on the channel. From that moment, native calls reach your object.- Passing a callback into the listener keeps the class free of widget code. A state-management object or a
StreamControllerworks equally well as the destination.
If your listener belongs to a widget's lifetime, register it in initState and unregister it in dispose:
@override
void dispose() {
BatteryEvents.setUp(null);
super.dispose();
}Passing null removes the handler. Without this step, a disposed object keeps receiving calls and holds references that stop it from being garbage collected.
Calling the API from Kotlin
On Android, construct the generated BatteryEvents class with the engine's binary messenger. Then call its methods. Each method takes a trailing callback that receives a Result.
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
class BatteryMonitor(
private val context: Context,
private val events: BatteryEvents,
) {
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
val state = when (status) {
BatteryManager.BATTERY_STATUS_CHARGING -> BatteryState.CHARGING
BatteryManager.BATTERY_STATUS_DISCHARGING -> BatteryState.DISCHARGING
BatteryManager.BATTERY_STATUS_FULL -> BatteryState.FULL
else -> BatteryState.UNKNOWN
}
events.onBatteryChanged(BatteryInfo(level.toLong(), state)) { result ->
result.onFailure { error ->
android.util.Log.w("BatteryMonitor", "Dart call failed", error)
}
}
}
}
fun start() {
context.registerReceiver(receiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
}
fun stop() {
context.unregisterReceiver(receiver)
}
}Create and start the monitor in MainActivity, next to the HostApi registration:
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val messenger = flutterEngine.dartExecutor.binaryMessenger
BatteryApi.setUp(messenger, BatteryApiImpl(this))
BatteryMonitor(this, BatteryEvents(messenger)).start()
}A BroadcastReceiver registered this way runs on the main thread, which is where channel calls must be made. Section "Threading" below covers other cases.
Calling the API from Swift
On iOS, the generated BatteryEvents class takes the FlutterBinaryMessenger. Its method takes a completion closure that receives a Result.
import Flutter
import UIKit
class BatteryMonitor {
private let events: BatteryEvents
private var observers: [NSObjectProtocol] = []
init(events: BatteryEvents) {
self.events = events
}
func start() {
UIDevice.current.isBatteryMonitoringEnabled = true
let names: [Notification.Name] = [
UIDevice.batteryLevelDidChangeNotification,
UIDevice.batteryStateDidChangeNotification,
]
for name in names {
let token = NotificationCenter.default.addObserver(
forName: name, object: nil, queue: .main
) { [weak self] _ in
self?.publish()
}
observers.append(token)
}
}
func stop() {
observers.forEach { NotificationCenter.default.removeObserver($0) }
observers.removeAll()
}
private func publish() {
let device = UIDevice.current
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
}
events.onBatteryChanged(info: BatteryInfo(level: level, state: state)) { result in
if case .failure(let error) = result {
print("Dart call failed: \(error)")
}
}
}
}Create it in AppDelegate once the Flutter view controller exists:
let controller = window?.rootViewController as! FlutterViewController
BatteryApiSetup.setUp(binaryMessenger: controller.binaryMessenger, api: BatteryApiImpl())
let monitor = BatteryMonitor(events: BatteryEvents(binaryMessenger: controller.binaryMessenger))
monitor.start()Keep a strong reference to monitor, for example in a property on AppDelegate. A local variable is released when the method returns, and the observers stop firing.
The queue: .main argument delivers notifications on the main thread, which satisfies the threading rule below.
Threading
Platform channel messages must be sent from the platform's main thread (the UI thread on Android, the main queue on iOS). A FlutterApi call from a background thread is a common source of crashes and silent failures. If your native work happens elsewhere, hop to the main thread first.
On Android:
import android.os.Handler
import android.os.Looper
private val mainHandler = Handler(Looper.getMainLooper())
fun publish(info: BatteryInfo) {
mainHandler.post {
events.onBatteryChanged(info) { /* handle result */ }
}
}On iOS:
DispatchQueue.main.async {
self.events.onBatteryChanged(info: info) { _ in }
}The reply to your call is also delivered on the main thread, so the callback needs no extra dispatch.
Failure modes and edge cases
- No handler registered. If native code calls the API before Dart has run
setUp, no one answers. The callback receives a failure, typically with the codechannel-error. This happens during cold start because native code often runs beforemain(). Either start the native monitor lazily, for example when a HostApi method such asstartMonitoring()is called, or accept that early events are lost. - Dart throws. An exception thrown inside your override travels back to native code as a failure
Result. This is why every call site should inspect the result, even forvoidmethods. - Fire and forget. Ignoring the callback is legal but hides these failures. At minimum, log them.
- Return values. A FlutterApi method can declare a return type. The Dart implementation returns the value, and native code receives it inside the callback's success case.
- Several engines. Each Flutter engine has its own messenger. If your app uses multiple engines or add-to-app screens, create one native client per messenger and call
setUpin each Dart isolate. Recent Pigeon versions also support amessageChannelSuffixargument for running several instances of the same API on one messenger. Check the generated code in your version. - Generated signatures vary by version. Older Pigeon releases use
FlutterErrorwhere newer ones usePigeonErrorin the SwiftResult, and the callback shape has changed over time. Read your generated file before you write call sites.
Choosing between a HostApi and a FlutterApi
Use a HostApi when Dart decides when something happens and wants an answer: read the battery now, open a settings screen. Use a FlutterApi when the platform decides: a lifecycle change, a notification tap, a hardware event. Many features need both. Dart starts monitoring through the HostApi, and native code reports changes through the FlutterApi.
Exercise
Your Android app calls events.onBatteryChanged(...) from a worker thread in a Executor, and the call sometimes fails or crashes. What is the cause, and what is the fix? Also, why might the very first call after launch fail with a channel-error even when called from the main thread?
Show answer
Channel messages must be sent from the main thread, so posting the call with Handler(Looper.getMainLooper()).post { ... } fixes the threading problem. The first call can fail with channel-error because Dart has not yet run BatteryEvents.setUp(...), so no handler is registered on the channel. Fix it by starting the native monitor only after Dart signals readiness, for example through a HostApi method, or by tolerating the lost early events.
Exercise
What do you pass to BatteryEvents.setUp in a widget's dispose method, and why?
Show answer
Pass null. It removes the registered handler, so native calls no longer reach a disposed object and the object can be garbage collected.