Sub topic 3
Implementing Channels on Android
This chapter assumes you know intermediate Dart and Flutter, can read Kotlin or Swift, and have seen MethodChannel and EventChannel in earlier chapters.
Implementing Channels on Android
On Android, a channel handler is attached to the Flutter engine's binary messenger. The channel name must match the Dart side exactly. This MainActivity answers the greet method and rejects a missing argument:
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
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()
}
}
}
}An EventChannel uses the same pattern with a StreamHandler. Its onListen starts the native source and sends values through events.success. Its onCancel stops the source.
Implementing Channels on iOS
On iOS, you create a FlutterMethodChannel with the same name, using the Flutter view controller's binary messenger:
let channel = FlutterMethodChannel(name: "com.example.app/greeting",
binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler { call, result in
if call.method == "greet" {
result("Hello")
} else {
result(FlutterMethodNotImplemented)
}
}Designing a Maintainable Platform Integration
Keep channel names in one Dart constant file. Wrap each channel in one Dart class, so widgets never call invokeMethod directly. Use the same method names and argument keys on Android and iOS.
Threading, Engine Lifecycle, and Resource Cleanup
Handlers run on the platform main thread. Send slow work to a background thread, then call result on the main thread. Release native resources in onCancel, because a cancelled subscription otherwise keeps running.
Testing Dart Wrappers and Channel Contracts
You can test a Dart wrapper without a device by mocking the channel:
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('com.example.app/greeting');
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'greet') {
return 'Hello, ${call.arguments['name']}';
}
throw MissingPluginException();
});
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
});
test('greet sends name and returns greeting', () async {
final result = await channel.invokeMethod<String>('greet', {'name': 'Ana'});
expect(result, 'Hello, Ana');
});
}Compatibility, Permissions, and Security
Channel arguments are untyped, so validate them on both the Dart and native sides. Declare any permission your native code needs in AndroidManifest.xml or Info.plist. Expose only the method names you need, because any Dart code in the app can call them.
Exercise
A Dart client calls greet without an name argument. What should the Android handler return, and why?
Show answer
It should call result.error("INVALID_ARGUMENT", "name is required", null). This reports a clear error to Dart, which throws a PlatformException, instead of crashing or returning a misleading value.