Sub topic 9
Choosing EventChannel for Native Streams
Assume you know intermediate Dart, Flutter Future and Stream APIs, and basic Android Kotlin or iOS Swift. This chapter focuses on choosing EventChannel when native code produces values over time.
When EventChannel fits
An EventChannel is a named bridge for a stream of messages from native code to Dart. Use it when Dart does not need to request each value:
- Sensor readings
- Location updates
- Download progress
- Connectivity changes
- Native notifications
- Playback or hardware state changes
A MethodChannel is usually better for a request-response operation such as “start recording” or “read the current battery level.” An EventChannel is better when the native side pushes multiple values after Dart subscribes.
Exposing a native stream to Dart
The Dart side creates an EventChannel and converts the untyped channel values into a useful type. The stream is lazy: native listening normally begins when the first Dart listener subscribes.
import 'package:flutter/services.dart';
class SensorApi {
static const _channel = EventChannel('com.example.app/sensor');
Stream<double> get values => _channel
.receiveBroadcastStream()
.map((value) => (value as num).toDouble());
}The channel codec supports values such as null, booleans, numbers, strings, lists, and maps whose keys and values are also supported values. Keep the contract simple. For example, document that this stream emits numeric readings rather than sometimes emitting strings or maps.
Dart code can consume the stream with listen, StreamBuilder, or another stream operator:
final subscription = SensorApi().values.listen(
(value) => print('Reading: $value'),
onError: (Object error) => print('Sensor error: $error'),
);
// Later, when the owner is disposed:
await subscription.cancel();Native stream lifecycle
The native handler receives onListen when Dart subscribes and onCancel when the subscription ends. Start native work in onListen, send values through events.success, and release resources in onCancel.
EventChannel(flutterEngine.dartExecutor.binaryMessenger, "com.example.app/sensor")
.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
events.success(21.5)
}
override fun onCancel(arguments: Any?) {
// Stop the native sensor subscription here.
}
})If native work fails, call events.error with a stable error code, a readable message, and optional details. Do not continue emitting after cancellation. Otherwise, a sensor, timer, or location listener can remain active after the Flutter screen disappears.
Exercise
Which channel should you choose for a native location service that emits position updates until Dart cancels its subscription?
Show answer
Use EventChannel. Start the location listener in onListen, emit positions with the event sink, report failures with events.error, and remove the listener in onCancel.