Sub topic 4
Handling method calls on Android with Kotlin
This chapter covers the Android half of a MethodChannel: receiving a call from Dart, reading its arguments, and sending exactly one reply. It assumes you can read basic Kotlin and have already seen the Dart side (invokeMethod) and the codec type table from earlier chapters. You should also know where android/app/src/main/kotlin/... sits in a Flutter project.
Where the handler lives
A Dart MethodChannel only works if native code registers a handler for the same channel name. On Android, the usual place is configureFlutterEngine in your FlutterActivity. Flutter calls it once the engine exists and is ready to accept channel registrations.
The registration needs three things:
- A
BinaryMessenger. UseflutterEngine.dartExecutor.binaryMessenger. - A channel name that matches the Dart string exactly, including case. A reverse-domain prefix such as
com.example.app/batteryavoids clashes with plugins. - A
MethodCallHandler, which is a function that receives aMethodCalland aResult.
This is the minimal handler from the plan:
import android.os.BatteryManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val channelName = "com.example.app/battery"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
.setMethodCallHandler { call, result ->
when (call.method) {
"getBatteryLevel" -> {
val manager = getSystemService(BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level >= 0) {
result.success(level)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
}
else -> result.notImplemented()
}
}
}
}Call super.configureFlutterEngine(flutterEngine) first. It registers the plugins listed in GeneratedPluginRegistrant, and skipping it breaks every plugin in your app.
The two objects you work with
MethodCall
MethodCall carries what Dart sent:
call.methodis the method name string, such as"getBatteryLevel".call.argumentsis the raw argument, typedAny?. It is whatever Dart passed toinvokeMethod, decoded by the standard codec.call.argument<T>("key")reads one entry when the arguments are a map. It returnsnullif the key is missing or the arguments are not a map.call.hasArgument("key")tells you whether a key exists, which lets you separate "missing" from "present and null".
Result
Result is how you answer. It has exactly three methods, and they match three outcomes on the Dart side:
| Kotlin call | What Dart sees |
|---|---|
| `result.success(value)` | The `Future` completes with `value`. Pass `null` for a void method. |
| `result.error(code, message, details)` | The `Future` throws a `PlatformException` with those three fields. |
| `result.notImplemented()` | The `Future` throws a `MissingPluginException`. |
The else -> result.notImplemented() branch in the example is worth keeping. Without it, an unknown method name leaves the Dart Future pending forever.
Follow one call through
The diagram shows one invokeMethod call from Dart to Android and back.
The call is asynchronous end to end. Dart does not block while the handler runs, but the handler itself runs on the Android main thread unless you move the work elsewhere.
Reading arguments safely
Arguments arrive as decoded Java types. A Dart Map<String, Object?> becomes a HashMap, a Dart String becomes a String, and a Dart int becomes an Int (or a Long when the value does not fit in 32 bits). The type is chosen at runtime from the value, so a wrong assumption fails at the call site, not at compile time.
Follow these rules:
- Read each argument with
call.argument<T>()and check fornullbefore using it. - Reply with an
errorfor bad input. Do not throw. - Treat numbers carefully. A Dart
intthat fits in 32 bits arrives asInt. Reading it asLongwithargument<Long>()throws aClassCastException. For values that might be large, readNumberand call.toLong().
val timeoutMs = call.argument<Number>("timeoutMs")?.toLong() ?: 5000LA handler with arguments and background work
Real handlers often do more than read a system service. The next example hashes a file. It reads arguments, validates them, does slow I/O off the main thread, and replies once on every path. It lives in its own class so MainActivity stays short.
import android.os.Handler
import android.os.Looper
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.concurrent.Executors
class FileHashHandler : MethodChannel.MethodCallHandler {
private val worker = Executors.newSingleThreadExecutor()
private val mainHandler = Handler(Looper.getMainLooper())
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method != "hashFile") {
result.notImplemented()
return
}
val path = call.argument<String>("path")
val algorithm = call.argument<String>("algorithm") ?: "SHA-256"
if (path == null) {
result.error("INVALID_ARGUMENT", "'path' is required.", null)
return
}
worker.execute {
try {
val hex = hash(path, algorithm)
mainHandler.post { result.success(hex) }
} catch (e: NoSuchAlgorithmException) {
mainHandler.post { result.error("BAD_ALGORITHM", e.message, algorithm) }
} catch (e: IOException) {
mainHandler.post { result.error("IO_ERROR", e.message, path) }
}
}
}
private fun hash(path: String, algorithm: String): String {
val digest = MessageDigest.getInstance(algorithm)
File(path).inputStream().use { input ->
val buffer = ByteArray(8192)
while (true) {
val read = input.read(buffer)
if (read < 0) break
digest.update(buffer, 0, read)
}
}
return digest.digest().joinToString("") { "%02x".format(it) }
}
fun dispose() {
worker.shutdown()
}
}Register it in MainActivity, and release it when the engine goes away:
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private var hashChannel: MethodChannel? = null
private var hashHandler: FileHashHandler? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val handler = FileHashHandler()
hashHandler = handler
hashChannel = MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"com.example.app/files"
).also { it.setMethodCallHandler(handler) }
}
override fun cleanupFlutterEngine(flutterEngine: FlutterEngine) {
hashChannel?.setMethodCallHandler(null)
hashHandler?.dispose()
hashChannel = null
hashHandler = null
super.cleanupFlutterEngine(flutterEngine)
}
}The matching Dart caller sends a map, which is what call.argument expects:
import 'package:flutter/services.dart';
class FileHasher {
static const MethodChannel _channel =
MethodChannel('com.example.app/files');
Future<String?> hashFile(String path, {String algorithm = 'SHA-256'}) {
return _channel.invokeMethod<String>('hashFile', {
'path': path,
'algorithm': algorithm,
});
}
}Three details in the Kotlin code matter:
- Slow I/O runs on
worker, so the main thread stays free for UI frames. - Replies go through
mainHandler.post. Platform channel replies must be sent from the main (platform) thread, and callingresultfrom a worker thread can crash or drop the reply depending on the engine version. - Each branch calls
resultexactly once.
The reply-once rule
A Result is a one-shot reply. Two failure modes follow from that:
- Replying twice. The second call throws an
IllegalStateException("Reply already submitted") on recent engine versions. It usually happens when atryblock callssuccessand a latercatchorfinallyalso callserror. - Never replying. The Dart
Futurestays pending. No timeout exists, so the awaiting code hangs and the caller never learns why. Earlyreturnstatements and unhandled branches inwhenare the usual cause.
If your handler throws an unchecked exception before replying, the engine catches the RuntimeException, logs it, and sends an error with the code "error" to Dart. That is a safety net, not a design. Reply with your own error codes so Dart can tell failures apart.
Lifecycle: cleaning up
A handler registered in configureFlutterEngine can outlive the thing it talks to. Two rules keep this safe:
- Set the handler to
nullincleanupFlutterEngine, as shown above, so the engine no longer calls into a destroyed activity. - Do not capture a destroyed
Activityin a long-lived handler. If a handler needs aContextand not an activity, useapplicationContext.
Common errors and fixes
| Symptom in Dart | Likely cause on Android | Fix |
|---|---|---|
| `MissingPluginException` | Channel name differs by one character, the handler is registered after the call, or you added native code and only hot reloaded. | Compare both strings. Do a full stop and rebuild, because hot reload and hot restart do not recompile Kotlin. |
| `MissingPluginException` for one method only | The method name is not in the `when`, so it reached `notImplemented()`. | Add the branch or fix the spelling. |
| `PlatformException(error, ...)` | An unchecked exception such as `ClassCastException` escaped the handler. | Read arguments with the correct type and validate them first. |
| The `await` never completes | A code path never calls `result`. | Check every branch, early return, and callback. |
| Crash or lost reply on a worker thread | `result` was called off the main thread. | Post the reply to `Looper.getMainLooper()`. |
Exercise
A Dart caller sends invokeMethod('resize', {'width': 300, 'height': 200}). The Kotlin handler reads val width = call.argument<Long>("width") and the app throws an exception inside the handler. What is the cause, what does Dart receive, and how do you fix it?
Show answer
The standard codec decodes a Dart int that fits in 32 bits as a Kotlin Int, so reading it as Long throws a ClassCastException. The engine catches the unchecked exception and sends an error with the code "error" to Dart, which surfaces as a PlatformException. Fix it by reading the value as Number and converting it, for example call.argument<Number>("width")?.toInt(). Then reply with result.error("INVALID_ARGUMENT", ...) if the value is null.
Exercise
In the FileHashHandler example, why does the success reply go through mainHandler.post instead of calling result.success(hex) directly inside worker.execute?
Show answer
Channel replies must be sent from the Android main (platform) thread. The code inside worker.execute runs on a background thread, so the reply is posted back to the main looper. This keeps the slow file reading off the main thread while the reply stays on the right one.