Sub topic 13
Streaming Events from Native to Dart
This chapter assumes that you have already configured Pigeon, can run its generator, and understand Dart Future and Stream values. You should also be able to read basic Kotlin or Swift.
A Pigeon EventChannelApi models a stream that starts in native code and is consumed by Dart. It is useful for battery changes, sensor readings, download progress, location updates, and other values that arrive repeatedly.
Choose the right direction
A HostApi lets Dart call native code. A FlutterApi lets native code call a Dart method. An EventChannelApi represents a subscription: Dart listens, while native code produces a sequence of typed events.
| API type | Direction | Best for |
|---|---|---|
| `HostApi` | Dart to native | Requesting one result |
| `FlutterApi` | Native to Dart | Calling a Dart method |
| `EventChannelApi` | Native to Dart | Delivering repeated events |
An event stream also has a lifecycle. Native code should begin producing values when Dart subscribes and stop when the subscription is canceled. This prevents sensors, timers, and observers from continuing to run after a screen has closed.
Define a typed event stream
Add an event API to the Pigeon input file:
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;
}
@EventChannelApi()
abstract class BatteryEvents {
Stream<BatteryInfo> onBatteryChanged();
}Stream<BatteryInfo> means that every event contains a BatteryInfo object. Pigeon generates the Dart stream interface and the matching platform-side types. Run the generator after changing the schema:
dart run pigeon --input pigeons/messages.dartThe generated code carries serialization and channel details. App code does not need to manually encode maps or remember an event-channel name.
Listen from Dart
The generated Dart API exposes the event method as a stream. Subscribe to it like any other Dart stream:
import 'dart:async';
import 'src/messages.g.dart';
class BatteryMonitor {
BatteryMonitor() : _events = BatteryEvents();
final BatteryEvents _events;
StreamSubscription<BatteryInfo>? _subscription;
void start() {
_subscription ??= _events.onBatteryChanged().listen((info) {
print('Battery: ${info.level}% (${info.state.name})');
});
}
Future<void> stop() async {
await _subscription?.cancel();
_subscription = null;
}
}Keep the subscription so that it can be canceled. In a Flutter widget, cancel it in dispose. If the generated API supports multiple listeners, decide whether each listener should create a native subscription or whether your application should share one subscription.
Implement and register the native side
Pigeon generates the platform contract, but it does not know which Android or iOS API should produce battery events. Your native implementation must:
- Subscribe to the platform battery source when the Dart stream gains a listener.
- Convert each platform value into the generated
BatteryInfotype. - Send values through the generated event handler.
- Remove the platform observer when the Dart stream is canceled.
- Register the generated event API with the Flutter engine's binary messenger.
The generated registration method and handler interface can vary with the Pigeon version and target language. Use the generated Kotlin or Swift file as the exact contract. Do not edit that file. Implement its interfaces in a separate source file.
Handle lifecycle and failures
A stream can fail after it has started. For example, a native sensor may become unavailable or permission may be revoked. Report that failure through the generated stream mechanism so Dart receives an error. Also consider what should happen when the app moves to the background.
Common mistakes include starting a native observer during app startup and never removing it, emitting events before Dart has subscribed, and sending a platform value that does not match the schema. Pigeon checks types at the boundary, but it cannot correct an incorrect lifecycle.
Exercise
Why should native code remove its observer when the Dart subscription is canceled?
Show answer
Cancellation marks the end of the consumer's interest. Removing the observer releases resources and prevents stale events from reaching a closed screen or object.