Sub topic 12
Streaming events from native code
A MethodChannel answers one question with one reply. Some native data keeps changing, such as battery level, connectivity, or sensor readings, and polling it wastes work and misses changes. An EventChannel solves this by exposing a native event source as a Dart Stream. This chapter adds a battery level stream to the battery_info plugin.
This chapter assumes you have the working battery_info plugin from the earlier chapters: the Dart class, the Kotlin and Swift plugin classes, and the MethodChannel named battery_info. You should also be comfortable with Dart streams (listen, StreamSubscription, cancel).
How an EventChannel differs from a MethodChannel
| Aspect | MethodChannel | EventChannel |
|---|---|---|
| Direction | Dart calls native, native replies once | Native pushes many values to Dart |
| Dart type | `Future<T>` | `Stream<T>` |
| Native interface (Android) | `MethodCallHandler` | `EventChannel.StreamHandler` |
| Native interface (iOS) | `FlutterPlugin.handle` | `FlutterStreamHandler` |
| Lifetime | One call | From first listener to last cancel |
| Errors | One `PlatformException` per call | Error events, and the stream stays open |
The channel name is the shared contract, as it is for method channels. This chapter uses battery_info/level_changes. A common convention is to prefix the event channel name with the plugin's method channel name, which prevents collisions with other plugins.
The stream lifecycle
Native code does not start sending events until Dart listens. When the first Dart listener subscribes, Flutter sends a listen message and the native onListen method runs. It receives an event sink, which is the object native code uses to push values. When the last listener cancels, onCancel runs and native code must stop producing events and release resources.
Because receiveBroadcastStream() returns a broadcast stream, several Dart listeners share one native subscription. The native side sees onListen once and onCancel once.
The Dart side
The event channel code from the topic plan goes into the BatteryInfo class. Extend it so that native error events become BatteryInfoException, the same type the method call uses.
import 'package:flutter/services.dart';
class BatteryInfoException implements Exception {
BatteryInfoException(this.code, this.message);
final String code;
final String? message;
@override
String toString() => 'BatteryInfoException($code, $message)';
}
class BatteryInfo {
static const MethodChannel _channel = MethodChannel('battery_info');
static const EventChannel _events = EventChannel('battery_info/level_changes');
Future<int> getBatteryLevel() async {
try {
final int? level = await _channel.invokeMethod<int>('getBatteryLevel');
return level!;
} on PlatformException catch (e) {
throw BatteryInfoException(e.code, e.message);
}
}
/// Emits the battery level (0 to 100) now and again whenever it changes.
Stream<int> get onBatteryLevelChanged => _events
.receiveBroadcastStream()
.map((dynamic event) => event as int)
.handleError((Object error) {
if (error is PlatformException) {
throw BatteryInfoException(error.code, error.message);
}
throw error;
});
}Use handleError and not a try/catch around an await for loop. An error event does not close the stream, and handleError keeps the subscription alive. A catch around await for would end the loop at the first error.
The Android side
On Android, ACTION_BATTERY_CHANGED is a sticky system broadcast. Registering a receiver for it delivers the current state immediately, so the stream emits an initial value without extra code. The plugin class now also implements EventChannel.StreamHandler.
package com.example.battery_info
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
class BatteryInfoPlugin : FlutterPlugin, MethodCallHandler, EventChannel.StreamHandler {
private lateinit var channel: MethodChannel
private lateinit var eventChannel: EventChannel
private lateinit var context: Context
private var receiver: BroadcastReceiver? = null
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
channel = MethodChannel(binding.binaryMessenger, "battery_info")
channel.setMethodCallHandler(this)
eventChannel = EventChannel(binding.binaryMessenger, "battery_info/level_changes")
eventChannel.setStreamHandler(this)
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"getBatteryLevel" -> {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level >= 0) {
result.success(level)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
}
else -> result.notImplemented()
}
}
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
val batteryReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
if (level < 0 || scale <= 0) {
events.error("UNAVAILABLE", "Battery level not available.", null)
} else {
events.success(level * 100 / scale)
}
}
}
receiver = batteryReceiver
context.registerReceiver(batteryReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
}
override fun onCancel(arguments: Any?) {
stopListening()
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
stopListening()
}
private fun stopListening() {
receiver?.let { context.unregisterReceiver(it) }
receiver = null
}
}onDetachedFromEngine calls stopListening() too. If the engine goes away while a Dart listener is active, onCancel may never run, and the receiver would leak. stopListening() is safe to call twice because it checks for null.
The iOS side
iOS has no sticky broadcast, so the handler sends the current level itself in onListen, then listens for UIDevice.batteryLevelDidChangeNotification. Battery monitoring must be switched on, or UIDevice reports -1 and sends no notifications.
import Flutter
import UIKit
public class BatteryInfoPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
private var eventSink: FlutterEventSink?
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "battery_info", binaryMessenger: registrar.messenger())
let eventChannel = FlutterEventChannel(name: "battery_info/level_changes", binaryMessenger: registrar.messenger())
let instance = BatteryInfoPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
eventChannel.setStreamHandler(instance)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getBatteryLevel":
UIDevice.current.isBatteryMonitoringEnabled = true
let level = UIDevice.current.batteryLevel
if level < 0 {
result(FlutterError(code: "UNAVAILABLE", message: "Battery level not available.", details: nil))
} else {
result(Int(level * 100))
}
default:
result(FlutterMethodNotImplemented)
}
}
public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
eventSink = events
UIDevice.current.isBatteryMonitoringEnabled = true
NotificationCenter.default.addObserver(
self,
selector: #selector(batteryLevelDidChange),
name: UIDevice.batteryLevelDidChangeNotification,
object: nil)
sendLevel()
return nil
}
public func onCancel(withArguments arguments: Any?) -> FlutterError? {
NotificationCenter.default.removeObserver(
self,
name: UIDevice.batteryLevelDidChangeNotification,
object: nil)
eventSink = nil
return nil
}
@objc private func batteryLevelDidChange() {
sendLevel()
}
private func sendLevel() {
let level = UIDevice.current.batteryLevel
if level < 0 {
eventSink?(FlutterError(code: "UNAVAILABLE", message: "Battery level not available.", details: nil))
} else {
eventSink?(Int(level * 100))
}
}
}The iOS simulator reports a battery level of -1, so you will see the UNAVAILABLE error there. Test on a physical device to see real values.
Rules that prevent common bugs
- Send events on the platform main thread. On Android,
onReceivefor a receiver registered this way runs on the main thread. If you produce events from a background thread, post them to the main looper first. On iOS, dispatch toDispatchQueue.mainbefore calling the sink. The previous chapter's threading rules apply here. - Never use the sink after
onCancel. Clear your reference (eventSink = nilon iOS) and unregister observers. A stale sink can crash or send events to a listener that no longer exists. - Release resources in both
onCanceland engine detach. Plugins that only clean up inonCancelcan leak when an engine is destroyed first. - Use
errorfor recoverable failures. An error event does not end the stream. To end it deliberately, callevents.endOfStream()on Android oreventSink(FlutterEndOfEventStream)on iOS. The Dart stream then completes. - Use only standard codec types. Events pass through the standard message codec, so send integers, doubles, strings, booleans, lists, and maps. Convert anything else, such as a custom class, to a map first.
- Do not assume replay. Anyone who subscribes later gets only new events, plus whatever initial value your
onListensends. This is why both implementations send the current level at the start.
Testing the stream
The test layer can mock the native stream handler, so the Dart mapping and error handling run without a device.
import 'package:battery_info/battery_info.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = EventChannel('battery_info/level_changes');
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockStreamHandler(channel, null);
});
test('emits levels from the platform in order', () {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockStreamHandler(
channel,
MockStreamHandler.inline(
onListen: (Object? arguments, MockStreamHandlerEventSink events) {
events.success(80);
events.success(79);
events.endOfStream();
},
),
);
expect(
BatteryInfo().onBatteryLevelChanged,
emitsInOrder(<Object>[80, 79, emitsDone]),
);
});
}Choosing between the two channel types
Use a MethodChannel when Dart asks and native answers once. Use an EventChannel when native code decides when data arrives. If you only need to push an occasional value from native to Dart and no stream semantics, a MethodChannel call in the opposite direction is possible but gives you no subscription lifecycle. The EventChannel start and stop signals are what let your plugin stop observing the system when nobody is listening.
Exercise
A Dart app subscribes to onBatteryLevelChanged, then a second widget subscribes to the same getter. How many times does the native onListen run, and when does onCancel run?
Show answer
onListen runs once, when the first listener subscribes, because receiveBroadcastStream() shares one native subscription among all Dart listeners. onCancel runs once, only after the last listener has cancelled. If the second widget cancels first, nothing happens on the native side.
Exercise
The Android plugin leaves the broadcast receiver registered after the Flutter engine is destroyed while a listener is still active. Which method should have cleaned it up, and why is onCancel not enough?
Show answer
onDetachedFromEngine should call the same cleanup that unregisters the receiver. When the engine is destroyed, Dart is gone and the cancel message may never be delivered, so onCancel might never run.