Sub topic 12
Streaming Events from Native Code
This chapter assumes you can write Dart, understand MethodChannel, and read basic Kotlin or Swift. You will learn how to expose a native event source as a Dart Stream.
When to Use an EventChannel
A MethodChannel is suitable for a request with one response, such as “read the current battery level.” An EventChannel is suitable for values that arrive repeatedly, such as sensor readings, location updates, or connectivity changes.
| Channel | Data flow | Dart API |
|---|---|---|
| `MethodChannel` | Request and one response | `Future<T>` |
| `EventChannel` | A sequence of values | `Stream<T>` |
An event channel has two sides:
- Dart subscribes to a stream.
- Native code starts sending events when a listener exists.
- Native code stops sending events when the last listener cancels.
- Each event must use a value supported by Flutter’s standard message codec, such as numbers, strings, lists, and maps.
Define the Dart API
Keep the channel name private. Expose a typed stream so callers do not need to know the platform-channel details.
import 'package:flutter/services.dart';
class BatteryInfo {
static const EventChannel _events =
EventChannel('battery_info/level_changes');
Stream<int> get onBatteryLevelChanged {
return _events.receiveBroadcastStream().map((dynamic event) {
if (event is! int) {
throw const FormatException('Invalid battery level event');
}
return event;
});
}
}receiveBroadcastStream creates a broadcast stream. Multiple widgets can listen to it, but the native source should still be managed carefully. The platform side receives listen and cancel callbacks as subscriptions change.
Connect the Native Event Source
On Android, create an EventChannel with the same name and attach a stream handler. The handler receives an EventSink, which sends events or errors to Dart.
private var sink: EventChannel.EventSink? = null
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
sink = events
startBatteryUpdates()
}
override fun onCancel(arguments: Any?) {
stopBatteryUpdates()
sink = null
}Your real implementation might register a battery receiver, sensor listener, or callback from a native SDK. Call sink?.success(value) for a normal event. Call sink?.error(code, message, details) when the source fails.
The iOS implementation follows the same lifecycle. Its stream handler stores the Flutter event sink in onListen, starts the native observer, and removes that observer in onCancel. Send values with sink?(value) and errors with FlutterError.
Handle Lifetime and Errors
Do not start a native observer when the plugin is registered. Start it when Dart receives its first subscription. Stop it when Dart cancels the subscription. This avoids battery use, memory leaks, and callbacks into an object that no longer exists.
Make sure each native callback sends values on the expected thread. If a platform SDK invokes callbacks on a background thread, marshal channel calls according to Flutter’s platform-channel requirements.
Exercise
Why should native code stop its event source in onCancel?
Show answer
A cancelled Dart subscription no longer needs events. Stopping the source prevents unnecessary work, battery use, and callbacks after the listener is gone.