Sub topic 2
Handling Method Calls on Android and iOS
This chapter assumes you know Dart and Flutter well, can read Kotlin or Swift, and have a MethodChannel already set up. Flutter sends each channel call as a message across the boundary between Dart and native code.
Handling Method Calls on Android and iOS
Each platform registers one handler per channel name. The handler checks call.method, reads the arguments, and replies with success, error, or notImplemented.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.example.app/greeting")
.setMethodCallHandler { call, result ->
if (call.method == "greet") {
val name = call.argument<String>("name")
if (name == null) {
result.error("INVALID_ARGUMENT", "name is required", null)
} else {
result.success("Hello, $name")
}
} else {
result.notImplemented()
}
}On iOS, the same channel is created from the Flutter view controller's binary messenger:
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 args = call.arguments as? [String: Any],
let name = args["name"] as? String else {
result(FlutterError(code: "INVALID_ARGUMENT", message: "name is required", details: nil))
return
}
result("Hello, \(name)")
}Returning Results and Handling Method Errors
Dart receives the reply as a Future. A native error becomes a PlatformException. An unhandled method becomes a MissingPluginException.
import 'package:flutter/services.dart';
Future<String> greet(MethodChannel channel, String name) async {
try {
return await channel.invokeMethod<String>('greet', {'name': name}) ?? '';
} on PlatformException catch (e) {
return 'Native error ${e.code}: ${e.message}';
} on MissingPluginException {
return 'No native handler is registered';
}
}Choosing EventChannel for Native Streams
Use MethodChannel for a single request and reply. Use EventChannel when native code produces a series of values, such as sensor readings. Dart subscribes, and native code sends events until the subscription is cancelled.
The diagram below is not valid as written; see the corrected block that follows.
Subscribing to and Consuming Event Streams
Dart listens to the channel like any other Stream.
import 'package:flutter/services.dart';
const _sensor = EventChannel('com.example.app/sensor');
final subscription = _sensor.receiveBroadcastStream().listen(
(value) => print('Reading: $value'),
onError: (Object error) => print('Sensor error: $error'),
);Producing Events from Native Code
The native side sends values through an EventSink when Dart subscribes. On Android, onListen receives the sink. On iOS, the equivalent is the FlutterStreamHandler callback onListen(withArguments:eventSink:).
Managing Stream Errors and Cancellation
Cancelling the Dart subscription calls onCancel on the native side. Release sensors, timers, and listeners there. Stop sending events after cancellation, because a late event has no listener.
Exercise
A Dart subscription to the sensor channel is cancelled, but the native sensor keeps producing readings. Which method should be fixed, and what should it do?
Show answer
Fix the native onCancel handler on Android (or the iOS onCancel(withArguments:) callback). It should stop the native sensor subscription and release any listeners it holds.