Sub topic 11
Producing Events from Native Code
This chapter assumes intermediate Dart and Flutter, plus basic Kotlin or Swift. You should understand Stream, asynchronous callbacks, and Flutter engine registration.
An EventChannel lets native code push values to Dart over time. Dart starts the flow by subscribing to the channel. Native code then receives an onListen callback, creates or connects to a resource, and sends values through an event sink. When Dart cancels the subscription, native code receives onCancel and must release that resource.
Registering a Native Event Handler
The channel name must match exactly on both sides. The native handler should start work only after onListen. This avoids collecting data when no Dart code can receive it.
On Android, EventSink.success sends a supported value to Dart. EventSink.error sends a stream error.
EventChannel(
flutterEngine.dartExecutor.binaryMessenger,
"com.example.app/sensor"
).setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(
arguments: Any?,
events: EventChannel.EventSink
) {
// Start the real sensor listener here.
events.success(21.5)
}
override fun onCancel(arguments: Any?) {
// Unregister the sensor listener and release resources here.
}
})For a real sensor, keep a reference to the listener and the event sink. Each native callback can call events.success(value). If the sensor fails, call events.error with a stable error code and message. Do not call success after cancellation.
Implementing the iOS Side
iOS uses FlutterStreamHandler. Store the sink while the subscription is active, and invalidate timers or observers when the subscription ends.
import Flutter
final class SensorStreamHandler: NSObject, FlutterStreamHandler {
private var timer: Timer?
private var sink: FlutterEventSink?
func onListen(
withArguments arguments: Any?,
eventSink events: @escaping FlutterEventSink
) -> FlutterError? {
sink = events
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {
[weak self] _ in
self?.sink?(Double.random(in: 0...100))
}
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
timer?.invalidate()
timer = nil
sink = nil
return nil
}
}The timer must run on a suitable run loop, and UI or framework APIs usually require the main thread. Move expensive processing to a background queue, then deliver channel events according to the platform API's thread requirements.
Exercise
Why should native code start a sensor listener in onListen instead of when the channel is registered?
Show answer
Registration can happen before any Dart subscriber exists. Starting in onListen ties the native resource to an active subscription and prevents unnecessary work.