Sub topic 9
Streaming events from iOS
This chapter covers the Swift half of an EventChannel: the object that turns native callbacks into events on a Dart Stream. It assumes you have read the chapters on the Dart side of EventChannel and on handling method calls on iOS. You should be comfortable with Stream.listen, Swift closures, and the ios/Runner folder of a Flutter project.
The iOS side of an EventChannel
On iOS, an EventChannel is backed by a FlutterEventChannel. You give it a name and a binary messenger. You also give it one object that conforms to the FlutterStreamHandler protocol. That protocol has two methods:
onListen(withArguments:eventSink:)runs when Dart starts listening. It receives aFlutterEventSink, which is a closure you call to push events to Dart.onCancel(withArguments:)runs when Dart stops listening. You use it to stop timers, remove observers, and release the sink.
The sink is only valid between those two calls. Treat onListen as "start producing" and onCancel as "stop producing and clean up everything you started".
The channel name must match the Dart EventChannel name exactly, including case. A mismatch does not fail loudly. Dart's listen call finds no handler and reports a MissingPluginException.
The listen and cancel lifecycle
Dart's receiveBroadcastStream() returns a broadcast stream. The platform is told to start when the first Dart subscriber arrives. It is told to stop when the last subscriber cancels. Extra subscribers in between share the same native stream and cause no extra native calls.
A first handler: a timer
The timer handler below reads an optional interval from the Dart arguments. It sends an incrementing counter and cleans up in onCancel.
import Flutter
class TickStreamHandler: NSObject, FlutterStreamHandler {
private var timer: Timer?
private var count = 0
func onListen(withArguments arguments: Any?,
eventSink events: @escaping FlutterEventSink) -> FlutterError? {
// Defensive: stop any timer left over from a previous listen.
timer?.invalidate()
let args = arguments as? [String: Any]
let intervalMs = args?["intervalMs"] as? Int ?? 1000
guard intervalMs > 0 else {
return FlutterError(code: "BAD_ARGS",
message: "intervalMs must be positive",
details: nil)
}
count = 0
timer = Timer.scheduledTimer(withTimeInterval: Double(intervalMs) / 1000.0,
repeats: true) { [weak self] _ in
guard let self = self else { return }
events(self.count)
self.count += 1
}
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
timer?.invalidate()
timer = nil
return nil
}
}Three details matter here.
- Arguments. Dart passes
argumentstoreceiveBroadcastStream, and iOS receives them asAny?. A DartMaparrives as[String: Any](anNSDictionary). A Dartintarrives as anNSNumber, which Swift can cast withas? Int. Always cast withas?. A force-cast crashes the app if Dart sends something unexpected. [weak self]. The timer retains its closure, and the closure would otherwise retain the handler. Weak capture avoids a retain cycle.onCancelinvalidates the timer anyway, but the weak capture protects you if cancel never arrives.- Idempotent start. Invalidating a leftover timer at the top of
onListenmeans a repeatedonListencannot leave two timers running and send every tick twice.
Registering the handler
Create the FlutterEventChannel with the same name Dart uses and attach the handler. In an app, this usually goes in AppDelegate:
import UIKit
import Flutter
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller = window?.rootViewController as! FlutterViewController
let events = FlutterEventChannel(name: "com.example.app/ticks",
binaryMessenger: controller.binaryMessenger)
events.setStreamHandler(TickStreamHandler())
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}The channel keeps its own reference to the handler, so you don't need to store the handler in a property. In a plugin, you would use registrar.messenger() instead of the controller's messenger, as the plugins chapter shows.
The matching Dart side passes the arguments and listens:
import 'package:flutter/services.dart';
class TickService {
static const EventChannel _events =
EventChannel('com.example.app/ticks');
Stream<int> ticks({int intervalMs = 1000}) => _events
.receiveBroadcastStream({'intervalMs': intervalMs})
.map((event) => event as int);
}
Future<void> main() async {
final sub = TickService().ticks(intervalMs: 500).listen(
print,
onError: (Object error) {
if (error is PlatformException) {
print('Native error: ${error.code} ${error.message}');
}
},
);
await Future<void>.delayed(const Duration(seconds: 3));
await sub.cancel(); // triggers onCancel in Swift
}The four things a handler can send
| What you do in Swift | What Dart sees |
|---|---|
| `events(value)` | A data event on the stream |
| `events(FlutterError(code:message:details:))` | An error event: a `PlatformException` delivered to `onError`. The stream stays open. |
| `events(FlutterEndOfEventStream)` | The stream closes and `onDone` runs |
| Return a `FlutterError` from `onListen` | The error does not reach your listener. It is reported through `FlutterError.reportError`. |
The distinction in the last two rows catches many people. If something goes wrong while the stream is running, send an error event through the sink. If setup fails in onListen, returning a FlutterError is accurate, but your Dart onError will not fire. If the Dart code needs to react, send the error through the sink instead. Make sure you have kept the sink first, which means doing your validation after you have stored or used events.
Sending an error event does not end the stream. Decide deliberately whether the stream should continue, and call events(FlutterEndOfEventStream) when the native source is finished for good.
A realistic handler: battery changes
Timers are good for demonstrations. Most real handlers register for a system notification. The next handler streams battery level changes. It stores the observer token so onCancel can remove it.
import Flutter
import UIKit
class BatteryStreamHandler: NSObject, FlutterStreamHandler {
private var observer: NSObjectProtocol?
func onListen(withArguments arguments: Any?,
eventSink events: @escaping FlutterEventSink) -> FlutterError? {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryState == .unknown {
device.isBatteryMonitoringEnabled = false
return FlutterError(code: "UNAVAILABLE",
message: "Battery level not available.",
details: nil)
}
// Send the current value immediately so Dart does not wait for a change.
events(Int(device.batteryLevel * 100))
observer = NotificationCenter.default.addObserver(
forName: UIDevice.batteryLevelDidChangeNotification,
object: nil,
queue: .main
) { _ in
let level = UIDevice.current.batteryLevel
if level < 0 {
events(FlutterError(code: "UNAVAILABLE",
message: "Battery level not available.",
details: nil))
} else {
events(Int(level * 100))
}
}
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
observer = nil
UIDevice.current.isBatteryMonitoringEnabled = false
return nil
}
}Notes on this handler:
queue: .mainmakes the notification block run on the main thread, which is where the sink must be called (see below).- The handler sends the current value in
onListen. Event streams have no "current value" of their own, so a late listener would otherwise wait for the next change. onCancelturns battery monitoring back off. A handler that enables a resource should disable it.- On the iOS Simulator,
batteryStateis typically.unknown, so this code takes the error path. Test it on a device.
Threading rules for the sink
Call the event sink on the main thread. If your data arrives on a background queue, such as a URLSession delegate or a Core Bluetooth callback, hop to the main queue first:
DispatchQueue.main.async {
events(payload)
}Skipping this step produces warnings or crashes that vary with the Flutter version, and the failures are intermittent. Calls to onListen and onCancel themselves arrive on the main thread.
Also keep these points in mind:
- Don't call
eventsafteronCancel. Keep the sink in an optional property if you need it outside the closure, and set it tonilinonCancel, as the Kotlin handler does. - Don't block the main thread inside
onListen. Start the work and return. - Only send channel-codec types:
NSNumber,String,FlutterStandardTypedData, arrays, and dictionaries of those, plusnil. A custom Swift struct throws at encoding time. Convert it to a dictionary first.
Common errors
MissingPluginExceptionon listen. The channel name differs between Dart and Swift, the handler was never registered, or you did a hot restart or hot reload after adding native code. Stop the app and rebuild.- Events arrive twice. An earlier timer or observer was never removed. Check that
onCancelundoes everythingonListencreated. - Nothing arrives after the first cancel and re-listen. The handler kept state from the previous run, for example a sink set to
nilthat is never reassigned. Reset all state inonListen. - Crash in
as! FlutterViewController. The root view controller is not aFlutterViewController, which happens with add-to-app or scene-based setups. Get the messenger from the correct engine or registrar instead.
Exercise
A Swift stream handler registers a NotificationCenter observer in onListen but only sets a local variable and never stores the token. Dart cancels its subscription. What goes wrong, and how do you fix it?
Show answer
The observer is never removed, so the notification block keeps running and calling the event sink after Dart has cancelled, and a new listen adds a second observer so events duplicate. Fix it by storing the token returned by addObserver(forName:object:queue:using:) in a property, and in onCancel calling NotificationCenter.default.removeObserver with that token and setting the property to nil.
Exercise
Your handler needs to tell Dart that the native source has finished and no more events will come. Which call do you make, and what happens on the Dart side?
Show answer
Call events(FlutterEndOfEventStream). The Dart stream closes, so onDone runs on the listener. Sending a FlutterError through the sink does not do this, because it only produces an error event and the stream stays open.