Sub topic 13
Streaming events from native to Dart
This chapter assumes you have read the earlier chapters on Pigeon. You should be able to generate code from a pigeons/messages.dart file and to implement a HostApi in Kotlin and Swift. You should also know what a FlutterApi is and be comfortable with Dart Stream and StreamSubscription.
When a stream is the right tool
Some native data arrives over time with no request from Dart: battery changes, sensor readings, connectivity changes, location updates. You have three ways to deliver such data.
| Approach | Direction of control | Fits | Weakness |
|---|---|---|---|
| Poll a `HostApi` method on a timer | Dart asks repeatedly | Rarely changing values | Wasted calls, and changes are seen late |
| `FlutterApi` callback | Native pushes whenever it likes | A few app-wide notifications | Native must hold the Dart API object. Nothing models start, stop or cancel |
| `EventChannelApi` | Dart subscribes, native pushes | Continuous or bursty data | One more generated surface to maintain |
Under the hood, a Pigeon EventChannelApi sits on Flutter's EventChannel. Without Pigeon you would call receiveBroadcastStream(), cast each event from dynamic, and match a channel name string on both sides. Pigeon generates the typed stream function and the native stream-handler base class, and it uses the same codec as your HostApi and FlutterApi, so data classes and enums are shared.
The key property is lifecycle. Native work starts when Dart starts listening and stops when Dart cancels. A FlutterApi has no such hook.
Declaring an EventChannelApi
You add the declaration to the same input file as your other APIs. An event API is an abstract class annotated with @EventChannelApi(). Each method describes one stream. The method's return type is the type of event that stream carries, and the method takes no parameters.
This example continues the battery example from earlier chapters and reuses BatteryInfo and BatteryState:
// pigeons/messages.dart (added to the existing file)
@EventChannelApi()
abstract class BatteryEvents {
BatteryInfo streamBatteryInfo();
}Here BatteryEvents is a new name, so it does not collide with any earlier example. Run the generator as before:
dart run pigeon --input pigeons/messages.dartThe generator produces three things from this declaration.
- A top-level Dart function
Stream<BatteryInfo> streamBatteryInfo({String instanceName = ''}). The name comes from the method name. - A Kotlin abstract class
StreamBatteryInfoStreamHandlerwith a staticregisterfunction. - A Swift class
StreamBatteryInfoStreamHandlerwith a matchingregisterfunction.
Event streams are a newer Pigeon feature. They need a recent Pigeon release, and support differs by output language. Check the Pigeon README and changelog for your version before you rely on this API on a target other than Dart, Kotlin or Swift.
Implementing the Kotlin handler
You subclass the generated handler and override onListen and onCancel. Pigeon passes you a PigeonEventSink<BatteryInfo>. The sink has three methods: success(event), error(code, message, details) and endOfStream().
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
class BatteryStreamHandler(private val context: Context) : StreamBatteryInfoStreamHandler() {
private var receiver: BroadcastReceiver? = null
override fun onListen(p0: Any?, sink: PigeonEventSink<BatteryInfo>) {
// A second onListen without onCancel can happen after a hot restart.
stop()
val newReceiver = object : BroadcastReceiver() {
override fun onReceive(c: Context, intent: Intent) {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100)
if (level < 0 || scale <= 0) {
sink.error("UNAVAILABLE", "Battery level not reported", null)
return
}
val percent = (level * 100L) / scale
sink.success(BatteryInfo(level = percent, state = BatteryState.UNKNOWN))
}
}
context.registerReceiver(newReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
receiver = newReceiver
}
override fun onCancel(p0: Any?) {
stop()
}
private fun stop() {
receiver?.let { context.unregisterReceiver(it) }
receiver = null
}
}
// In MainActivity:
// override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
// super.configureFlutterEngine(flutterEngine)
// StreamBatteryInfoStreamHandler.register(
// flutterEngine.dartExecutor.binaryMessenger,
// BatteryStreamHandler(this)
// )
// }The first parameter is the optional arguments object that EventChannel passes through. Pigeon streams do not use it, so the code ignores it. The Dart int arrives as a Kotlin Long, as in the earlier chapters, which is why the percentage is computed with 100L.
ACTION_BATTERY_CHANGED is a sticky broadcast. Registering the receiver delivers the current value at once, so the Dart listener gets an initial event without waiting for a change.
Implementing the Swift handler
The Swift side has the same shape. The class overrides onListen(withArguments:sink:) and onCancel(withArguments:).
import Flutter
import UIKit
class BatteryStreamHandler: StreamBatteryInfoStreamHandler {
private var observer: NSObjectProtocol?
override func onListen(withArguments arguments: Any?, sink: PigeonEventSink<BatteryInfo>) {
stop()
UIDevice.current.isBatteryMonitoringEnabled = true
func emit() {
let level = Int64(max(UIDevice.current.batteryLevel, 0) * 100)
sink.success(BatteryInfo(level: level, state: .unknown))
}
observer = NotificationCenter.default.addObserver(
forName: UIDevice.batteryLevelDidChangeNotification,
object: nil,
queue: .main
) { _ in emit() }
emit() // send the current value immediately
}
override func onCancel(withArguments arguments: Any?) {
stop()
}
private func stop() {
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
observer = nil
UIDevice.current.isBatteryMonitoringEnabled = false
}
}
// In AppDelegate, after the Flutter view controller is available:
// let controller = window?.rootViewController as! FlutterViewController
// StreamBatteryInfoStreamHandler.register(
// with: controller.binaryMessenger,
// streamHandler: BatteryStreamHandler()
// )On iOS, batteryLevel is -1 while monitoring is off or on a simulator. The max(..., 0) guard turns that into 0, as the earlier HostApi example did. If 0 would mislead your users, send an error through the sink instead.
Consuming the stream in Dart
On the Dart side you only call the generated function and listen to what it returns.
import 'dart:async';
import 'src/messages.g.dart';
StreamSubscription<BatteryInfo> watchBattery() {
return streamBatteryInfo().listen(
(info) => print('Battery ${info.level}% (${info.state.name})'),
onError: (Object error) {
print('Battery stream error: $error');
},
onDone: () => print('Battery stream closed'),
);
}The events are BatteryInfo objects, not dynamic. Nothing in this code mentions a channel name, a cast, or a codec.
How the pieces map to Dart stream behavior:
- The first
listencall triggers nativeonListen. Cancelling the last subscription triggersonCancel. This follows the broadcast stream semantics of Flutter'sEventChannel. sink.success(event)becomes a data event,sink.error(...)becomes an error event, andsink.endOfStream()closes the stream and firesonDone.- An error event does not end the stream. Dart keeps listening unless you set
cancelOnError: trueinlisten.
Sending several kinds of events
One stream can carry more than one kind of event. Declare a sealed base class in the input file and have each event type extend it. Pigeon generates the corresponding sealed hierarchy in each language, so the Dart code can use an exhaustive switch.
// pigeons/messages.dart
sealed class ChargeEvent {}
class LevelChanged extends ChargeEvent {
LevelChanged({required this.level});
int level;
}
class StateChanged extends ChargeEvent {
StateChanged({required this.state});
BatteryState state;
}
@EventChannelApi()
abstract class ChargeEvents {
ChargeEvent streamChargeEvents();
}import 'src/messages.g.dart';
String describe(ChargeEvent event) {
return switch (event) {
LevelChanged(:final level) => 'Level is now $level%',
StateChanged(:final state) => 'State is now ${state.name}',
};
}If you later add a third subclass, the Dart switch stops compiling until you handle it. A string-keyed map sent over a raw EventChannel gives you no such check.
Threading and lifecycle rules
Event streams add a few constraints to the general threading rules from earlier chapters.
- Call the sink from the platform's main thread. Platform channel messages are posted to the Flutter engine from the main thread. A Kotlin background thread must use
Handler(Looper.getMainLooper()).post { sink.success(...) }. A Swift background queue must useDispatchQueue.main.async { sink.success(...) }. The examples above are already on the main thread because broadcast receivers and notification observers withqueue: .mainrun there. - Always release the source in
onCancel. A forgotten receiver or observer keeps running and keeps a reference to a dead sink. This drains battery and may crash when it sends to a closed channel. - Drop the sink after
onCancel, and never call it afterward. Keep it in a nullable property, set it to null inonCancel, and check before sending. - Expect
onListento run twice in a row after a hot restart. The Dart isolate restarts but the native handler does not always receive a cancel first. Replace the old source at the start ofonListen, as both examples above do withstop(). - Do not flood the channel. Every event is serialized and crosses the boundary. A sensor firing at 200 Hz should be sampled or batched on the native side, for example into a list of readings per 50 ms.
Testing code that uses an event stream
The generated stream function is a top-level function, so tests cannot substitute it by subclassing. The usual remedy is to inject the function as a constructor parameter, which keeps the production default and lets a test pass a plain Stream.
// lib/battery_repository.dart
import 'src/messages.g.dart';
class BatteryRepository {
BatteryRepository({Stream<BatteryInfo> Function()? source})
: _source = source ?? streamBatteryInfo;
final Stream<BatteryInfo> Function() _source;
Stream<int> levels() => _source().map((info) => info.level).distinct();
}// test/battery_repository_test.dart
import 'dart:async';
import 'package:app/battery_repository.dart';
import 'package:app/src/messages.g.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('levels skips repeated values', () async {
final controller = StreamController<BatteryInfo>();
final repository = BatteryRepository(source: () => controller.stream);
final future = repository.levels().take(2).toList();
controller.add(BatteryInfo(level: 80, state: BatteryState.charging));
controller.add(BatteryInfo(level: 80, state: BatteryState.charging));
controller.add(BatteryInfo(level: 79, state: BatteryState.discharging));
expect(await future, [80, 79]);
await controller.close();
});
}This test never touches a platform channel. It checks your Dart logic with the same typed events the real stream would deliver. Pigeon also generates test-only support for HostApi methods, but you should not expect equivalent mocks for event streams. Check your generated output for your version.
Common errors
- Stream never emits. The native handler was never registered, or it was registered on a different binary messenger, such as a different engine in an add-to-app setup. Check that
registerran with the same engine that runs the Dart code. MissingPluginExceptionon listen. The generated names orinstanceNamediffer between Dart and native, or the registration code was not reached becauseconfigureFlutterEngineor the app delegate setup returned early.- Events arrive but the app crashes with a thread error. The sink was called from a background thread. Post to the main thread first.
- Duplicate events after navigating back and forth. An earlier subscription was never cancelled. Cancel it in
dispose, or useStreamBuilderso the framework does it. - Dart receives an error but the stream continues. This is the expected behavior. Handle
onError, or usecancelOnError: trueif an error should end the subscription.
Exercise
A native handler's onListen starts a location source, but nothing in onCancel stops it. The Dart screen that listens is closed and reopened five times. What goes wrong, and how do you fix it?
Show answer
Each reopening calls onListen again, so up to five location sources may be running and sending events into stale or closed sinks, which wastes battery and can crash. Fix it by storing the source (or its listener) in a property, stopping it in onCancel, and also stopping any previous source at the start of onListen. Also drop the sink reference in onCancel and check for null before sending.
Exercise
You need one Pigeon stream that reports both connectivity type changes (wifi, cellular) and signal strength changes (an int). How do you declare it so the Dart consumer is forced to handle both kinds of event?
Show answer
Declare a sealed class base type, for example NetworkEvent, with two subclasses such as TypeChanged and StrengthChanged. Declare one @EventChannelApi() method that returns NetworkEvent. In Dart, use a switch expression over the event. Because the base class is sealed, the compiler requires both cases to be handled.