Sub topic 10
Subscribing to and Consuming Event Streams
This chapter assumes intermediate Dart and Flutter knowledge, including Stream, Future, widgets, and dispose. It also assumes that native code has registered an EventChannel with the same name as the Dart channel.
When to Use an EventChannel
An EventChannel carries a sequence of values from native code to Dart. Use it for data that arrives over time, such as sensor readings, location updates, download progress, or connectivity changes.
A MethodChannel represents a request and one response. An EventChannel represents a subscription that can produce many responses.
Creating a Typed Dart Stream
receiveBroadcastStream returns a stream whose values are dynamically typed. Convert each value at the boundary so the rest of the application can use a clear type.
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());
}
class SensorController {
final SensorApi api;
StreamSubscription<double>? _subscription;
SensorController(this.api);
void start(void Function(double value) onValue) {
_subscription = api.values.listen(
onValue,
onError: (Object error, StackTrace stackTrace) {
print('Sensor error: $error');
},
);
}
Future<void> stop() async {
await _subscription?.cancel();
_subscription = null;
}
}Calling listen creates a StreamSubscription. Keep that subscription so you can cancel it later. Cancellation matters because it tells the native side that this Dart consumer no longer needs updates.
Handling Values and Errors
Events arrive asynchronously, so the listener must not assume that a value is available immediately. Validate or convert incoming values before exposing them to widgets.
A channel error reaches the stream as an error event. Handle expected failures, such as missing permissions, in the listener or in a higher-level service. Do not silently ignore errors.
In a StatefulWidget, start the subscription in initState and cancel it in dispose. If the native source depends on screen visibility, also cancel it when the screen becomes inactive.
Exercise
Why should an EventChannel subscription be cancelled when a widget is disposed?
Show answer
Cancellation stops Dart from receiving unwanted events and gives native code an opportunity to release sensors, listeners, timers, or other resources.