Sub topic 12
Managing Stream Errors and Cancellation
This chapter assumes intermediate Dart and Flutter, including Future, Stream, and StreamSubscription. It also assumes basic Kotlin or Swift so you can read the native event handler.
An EventChannel carries a native event stream into Dart. A healthy stream can still end in two different ways:
- An error reports that an event could not be produced.
- Cancellation tells the native side that Dart no longer wants events.
Treat both as part of the channel contract.
Reporting errors from native code
The native event handler uses an error callback rather than throwing an exception across the platform boundary. In Android Kotlin, call events.error with a stable code, a readable message, and optional details.
EventChannel(
flutterEngine.dartExecutor.binaryMessenger,
"com.example.app/sensor"
).setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
val sensorAvailable = false
if (!sensorAvailable) {
events.error(
"SENSOR_UNAVAILABLE",
"The required sensor is not available",
null
)
return
}
events.success(21.5)
}
override fun onCancel(arguments: Any?) {
// Stop the native sensor subscription here.
}
})Dart receives this as a stream error. Handle it with try and await for, or with StreamSubscription.onError.
import 'dart:async';
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());
}
Future<void> readSensor() async {
try {
await for (final value in SensorApi().values) {
print('Sensor value: $value');
}
} on PlatformException catch (error) {
print('Sensor failed: ${error.code}: ${error.message}');
} on MissingPluginException {
print('The native channel is not registered on this platform.');
}
}Do not silently convert every error into an empty stream. The caller may need to show an error, request permission, or retry later.
Cancellation and resource cleanup
Dart cancellation happens when a subscription is canceled, when a widget disposes its subscription, or when the stream ends. The platform side receives onCancel. Release sensors, location listeners, timers, and other native resources there.
Common mistakes
- Calling
events.errorrepeatedly after the stream has already failed. - Forgetting cleanup in
onCancel, causing duplicate listeners or battery use. - Assuming cancellation is only caused by errors. Normal widget disposal also cancels subscriptions.
- Using a new channel name on one platform. Channel names must match exactly.
- Reporting unstable error strings instead of codes that Dart can test.
Exercise
A Flutter screen subscribes to a location EventChannel and cancels its subscription in dispose. Which native callback should stop the location listener?
Show answer
The native StreamHandler.onCancel callback.