Sub topic 7
Receiving a stream of events with EventChannel
This chapter covers the Dart side of an EventChannel. It assumes you can use Stream, StreamSubscription, and async/await in Dart. It also assumes you have already written a MethodChannel call, so you know what a channel name and a binary messenger are. The Android and iOS handlers get their own chapters. Here the focus is how Dart subscribes, what the stream does, and the mistakes that cause leaks or missing events.
Why a stream, not a method call
A MethodChannel call is one request and one reply. Many native features do not fit that shape. Battery state changes, location updates, sensor readings, and connectivity changes all produce a series of values over time, and you cannot know in advance when the next one will arrive.
An EventChannel models this as a Dart Stream. Native code pushes events. Dart listens. When Dart stops listening, native code is told to stop.
| Question | MethodChannel | EventChannel |
|---|---|---|
| Who starts the exchange? | Dart | Dart subscribes, then native pushes |
| How many values? | One result per call | Zero or more events |
| Dart type | `Future<T>` | `Stream<T>` |
| Ends when | The reply arrives | Dart cancels or native closes the stream |
The Dart API
An EventChannel has a name and, optionally, a codec. It has one method you will use: receiveBroadcastStream.
import 'package:flutter/services.dart';
class TickService {
static const EventChannel _events =
EventChannel('com.example.app/ticks');
Stream<int> get ticks =>
_events.receiveBroadcastStream().map((event) => event as int);
}
// Usage:
// final sub = TickService().ticks.listen(print);
// ...
// await sub.cancel(); // triggers onCancel on the native sideThree details matter here.
- The channel name must match the name used on the native side exactly. The names are plain strings, so a typo produces no compile error. The stream simply fails when you listen.
receiveBroadcastStreamreturns aStream<dynamic>. The channel does not know your event type, so you cast or map each event yourself.- The
.mapcall creates a new stream that wraps the channel stream. The castevent as intruns for each event, and it throws aTypeErrorif native code sends something else.
Optional arguments
receiveBroadcastStream accepts one optional argument. The value goes to native code in the onListen call. It is useful when one native handler serves several configurations, such as a sampling interval or a sensor type.
import 'package:flutter/services.dart';
class SensorService {
static const EventChannel _events =
EventChannel('com.example.app/sensor');
Stream<double> readings({required int intervalMs}) {
return _events
.receiveBroadcastStream(<String, Object>{'intervalMs': intervalMs})
.map((event) => (event as num).toDouble());
}
}The argument is encoded with the channel's codec, so it must use types the standard codec supports. The native handler receives it in onListen as arguments. Casting to num before calling toDouble() is deliberate: some platforms deliver a whole-number value as an integer even when the underlying measurement is a double.
What "broadcast" means here
The method name says broadcast, but the stream behaves in a specific way that surprises people.
- The stream is lazy. Nothing happens on the native side until the first listener subscribes.
- The first listener triggers a
listenmessage to native code, which callsonListen. - When the last listener cancels, Dart sends a
cancelmessage, which callsonCancel. - Each call to
receiveBroadcastStream()creates a new stream. A second call does not share a native subscription with the first stream. It performs its own listen and cancel exchange.
The last point has a practical consequence. If you call receiveBroadcastStream() in two places, native code may see two onListen calls. Most native handlers keep a single sink, so the second call can replace the first sink and the first listener silently stops receiving events. Create the stream once and share it.
import 'package:flutter/services.dart';
class TickService {
static const EventChannel _events =
EventChannel('com.example.app/ticks');
// One stream object for the whole app. Listeners share it.
late final Stream<int> ticks =
_events.receiveBroadcastStream().map((event) => event as int);
}Because map on a broadcast stream returns a broadcast stream, several widgets can call listen on ticks. The native side is subscribed while at least one listener exists.
The lifecycle of a subscription
The following diagram shows the messages exchanged when Dart listens, receives events, and cancels.
The sequence has these properties:
- Events travel from native to Dart only. Dart cannot send data back on the same stream except through the
listenarguments. - The
listenandcancelmessages are the only control messages. Everything between them is events. - Events keep their order. They arrive on the Dart main isolate one at a time.
Errors and the end of a stream
Native code can end a stream in two ways, and it can also report an error without ending it.
- Error event. The native sink calls its error method with a code, message, and details. Dart receives a
PlatformExceptionthrough the stream's error channel. The stream stays open and later events still arrive. - End of stream. The native sink calls
endOfStream. The Dart stream completes andonDonefires. - No handler. If native code never registered a handler for this channel name, Dart gets a
MissingPluginExceptionwhen it listens.
Handle errors by providing onError to listen, or by using handleError on the stream.
import 'dart:async';
import 'package:flutter/services.dart';
class TickListener {
static const EventChannel _events =
EventChannel('com.example.app/ticks');
StreamSubscription<int>? _sub;
void start(void Function(int) onTick) {
_sub = _events
.receiveBroadcastStream()
.map((event) => event as int)
.listen(
onTick,
onError: (Object error) {
if (error is PlatformException) {
print('Native error: ${error.code} ${error.message}');
} else if (error is MissingPluginException) {
print('No native handler registered for this channel.');
} else {
print('Unexpected error: $error');
}
},
onDone: () => print('Native side closed the stream.'),
cancelOnError: false,
);
}
Future<void> stop() async {
await _sub?.cancel();
_sub = null;
}
}The default value of cancelOnError is false, which suits an EventChannel. Native error events are often transient, such as one failed sensor read, and you usually want to keep listening. Set it to true only if an error means the source is unusable.
A MissingPluginException is not the same as a PlatformException. It means no native code answered at all. The common causes are a mismatched channel name, a handler registered after Dart started listening, or a hot restart where the native side was not rebuilt. A hot restart resets Dart state but does not rerun native registration, so after you add native code you need a full stop and rebuild.
Cancellation matters
Cancelling the subscription is the only way native code learns that Dart no longer needs events. If you never cancel, the native source keeps running. That wastes battery and memory, and on some sources, such as location, it keeps hardware active.
In a StatefulWidget, cancel in dispose.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class TickCounter extends StatefulWidget {
const TickCounter({super.key});
@override
State<TickCounter> createState() => _TickCounterState();
}
class _TickCounterState extends State<TickCounter> {
static const EventChannel _events =
EventChannel('com.example.app/ticks');
StreamSubscription<int>? _sub;
int _latest = -1;
@override
void initState() {
super.initState();
_sub = _events
.receiveBroadcastStream()
.map((event) => event as int)
.listen((value) {
setState(() => _latest = value);
});
}
@override
void dispose() {
_sub?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Text(_latest < 0 ? 'Waiting...' : 'Tick $_latest');
}
}If you use StreamBuilder instead, the builder subscribes when it is built and cancels when it is removed from the tree. Pass it a stream that you created once, not a new receiveBroadcastStream() call inside build, or each rebuild would create a new stream and a new native subscription.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| `MissingPluginException` on listen | Channel name differs, or no handler registered | Compare names character by character, then do a full rebuild |
| No events arrive, no error | Native sink was never given a value, or a second `onListen` replaced the first sink | Share one Dart stream and check the native code calls the sink |
| `TypeError` inside `map` | Native sent a type other than the one you cast to | Check the codec type mapping, and cast to `num` for numbers |
| Events continue after leaving the screen | Subscription never cancelled | Cancel in `dispose` or use `StreamBuilder` |
| Duplicate events after a hot restart | Old native source still running | Stop the app and rebuild, and make `onCancel` release the source |
Choosing your own structure
Keep the channel behind a small class, as TickService does. Callers then see a typed Stream<int> and never touch the channel name or the casting. That gives you one place to change if the native contract changes, and one place to replace the channel with a fake in tests, which a later chapter covers.
Exercise
A screen calls receiveBroadcastStream() inside its build method and passes the result to a StreamBuilder. Users report that the native sensor restarts every time the screen rebuilds, and sometimes events stop arriving. Explain the cause and give the fix.
Show answer
Each call to receiveBroadcastStream() creates a new stream with its own listen and cancel exchange. Every rebuild creates a new stream, so StreamBuilder cancels the old subscription and subscribes to the new one. Native code gets onCancel and onListen repeatedly, which restarts the sensor. If a new onListen arrives before the old one is cleaned up, the handler's single sink can be replaced, and events stop reaching one of the listeners. The fix is to create the stream once, for example in initState or in a service field such as late final Stream<int> ticks, and pass that same stream object to StreamBuilder on every build.
Exercise
Native code sends the value 3 on a channel that measures temperature in degrees. Your Dart code uses .map((event) => event as double) and throws a TypeError. What change makes the code safe, and why?
Show answer
The standard codec delivers a whole number as an integer, so the Dart value is an int even though the measurement is conceptually a double. Casting int to double with as fails. Use (event as num).toDouble(), which accepts both int and double. You can also fix it in native code by always sending a floating-point value.