Sub topic 13
Implementing Channels on Android
Assume you know intermediate Dart and Flutter, can read Kotlin, and understand Future, Stream, and asynchronous callbacks. This chapter shows how Android code registers handlers for Flutter platform channels.
Registering channels in the Flutter activity
Android receives channel messages through Flutter’s binary messenger. A MethodChannel handles request-response calls. An EventChannel handles a stream of events.
Channel names are strings. Android and Dart must use exactly the same name, including capitalization and punctuation.
package com.example.app
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val methodName = "com.example.app/greeting"
private val eventName = "com.example.app/sensor"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
methodName
).setMethodCallHandler { call, result ->
when (call.method) {
"greet" -> {
val name = call.argument<String>("name")
if (name.isNullOrBlank()) {
result.error(
"INVALID_ARGUMENT",
"name is required",
null
)
} else {
result.success("Hello, $name")
}
}
else -> result.notImplemented()
}
}
EventChannel(
flutterEngine.dartExecutor.binaryMessenger,
eventName
).setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(
arguments: Any?,
events: EventChannel.EventSink
) {
events.success(21.5)
}
override fun onCancel(arguments: Any?) {
// Stop a sensor listener or other native resource here.
}
})
}
}configureFlutterEngine runs when the activity connects to a Flutter engine. The binaryMessenger transports encoded messages between Dart and Android.
A method handler must complete the result exactly once. Use success for a value, error for a controlled failure, and notImplemented when the method is unsupported. Returning nothing leaves the Dart Future waiting indefinitely.
Handling arguments safely
Use call.argument<T>("key") to read a typed argument. It can return null when the key is missing or has the wrong type, so validate it before using it. Never trust values merely because they came from your own Dart code. A future plugin version or another engine may send different data.
Event subscriptions and cleanup
For an EventChannel, onListen starts the native producer when Dart subscribes. Call events.success(value) for each event. Call events.error(code, message, details) for a stream failure. onCancel must detach listeners, stop timers, and release resources.
Run platform work on an appropriate thread. Keep quick validation and result delivery simple, but move blocking I/O or sensor processing off the main thread. Also consider the activity and engine lifecycle: unregister native listeners when a stream is canceled or the engine is detached.
Exercise
What should an Android method handler return when Dart calls a method name that it does not support?
Show answer
It should call result.notImplemented().