Sub topic 14
Implementing Channels on iOS
This chapter assumes intermediate Dart and Flutter knowledge, including Future, Stream, and asynchronous callbacks. You should also know basic Swift and understand how an iOS Flutter app uses an AppDelegate.
On iOS, Flutter platform channels connect Dart code to Swift or Objective-C code. The Dart side creates a channel with a name. Swift creates a channel with the same name and registers a handler. The channel name and message shape form a contract between both sides.
| Dart channel | iOS counterpart | Best for |
|---|---|---|
| `MethodChannel` | `FlutterMethodChannel` | One request and one response |
| `EventChannel` | `FlutterEventChannel` | A stream of native updates |
Registering a MethodChannel
Register channels after obtaining the FlutterViewController. The controller provides the binaryMessenger, which transports encoded messages between Dart and Swift.
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 channel = FlutterMethodChannel(
name: "com.example.app/greeting",
binaryMessenger: controller.binaryMessenger
)
channel.setMethodCallHandler { call, result in
guard call.method == "greet" else {
result(FlutterMethodNotImplemented)
return
}
guard
let arguments = call.arguments as? [String: Any],
let name = arguments["name"] as? String,
!name.isEmpty
else {
result(FlutterError(
code: "INVALID_ARGUMENT",
message: "name is required",
details: nil
))
return
}
result("Hello, \(name)")
}
GeneratedPluginRegistrant.register(with: self)
return super.application(
application,
didFinishLaunchingWithOptions: launchOptions
)
}
}result must be called exactly once for a handled method. Return a value for success, FlutterError for a known failure, or FlutterMethodNotImplemented for an unsupported method.
Producing an EventChannel stream
An EventChannel uses a stream handler. onListen starts native work when Dart subscribes. onCancel stops that work when Dart cancels its subscription.
final class SensorStreamHandler: NSObject, FlutterStreamHandler {
private var timer: Timer?
func onListen(
withArguments arguments: Any?,
eventSink events: @escaping FlutterEventSink
) -> FlutterError? {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
events(21.5)
_ = self
}
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
timer?.invalidate()
timer = nil
return nil
}
}Create a FlutterEventChannel with the same name used by Dart and assign this handler with setStreamHandler. Replace the timer with the real sensor, location, or notification source in production.
Lifecycle and iOS differences
Native APIs often require permissions. Request permission before sending data, and report denial through a clear error or event. Deliver channel results on the expected thread, usually the main thread when interacting with UIKit. Always release observers, timers, delegates, and sensor subscriptions in onCancel or another lifecycle callback.
Exercise
What should an iOS MethodChannel handler return when Dart invokes a method that Swift does not support?
Show answer
It should call result(FlutterMethodNotImplemented).