Sub topic 6
Implementing the Android Side in Kotlin
This chapter assumes that you can build a Flutter app, read basic Kotlin, and understand how Android services are accessed. You should also have the plugin project generated with an Android implementation and a matching pubspec.yaml entry.
The Android side receives method calls from Dart through a platform channel. A platform channel is a named communication path between Dart and native code. The Dart and Kotlin sides must use the same channel name and method name.
sequenceDiagram
participant Dart
participant Channel
participant Kotlin
participant Android
Dart->>Channel: invokeMethod("getBatteryLevel")
Channel->>Kotlin: MethodCall
Kotlin->>Android: Read BatteryManager
Android-->>Kotlin: Battery percentage
Kotlin-->>Channel: result.success(level)
Channel-->>Dart: Future<int>The plugin class implements two Flutter interfaces:
FlutterPlugincontrols attachment to and detachment from the Flutter engine.MethodCallHandlerreceives calls sent through aMethodChannel.
Create the plugin and channel
Flutter calls onAttachedToEngine when the plugin becomes available to a Flutter engine. Create the channel there and register the plugin as its handler.
Store the application context rather than an Activity context. The application context remains valid for the lifetime of the engine and avoids accidentally retaining an Activity.
package com.example.battery_info
import android.content.Context
import android.os.BatteryManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
class BatteryInfoPlugin : FlutterPlugin, MethodCallHandler {
private lateinit var channel: MethodChannel
private lateinit var context: Context
override fun onAttachedToEngine(
binding: FlutterPlugin.FlutterPluginBinding
) {
context = binding.applicationContext
channel = MethodChannel(
binding.binaryMessenger,
"battery_info"
)
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"getBatteryLevel" -> {
val manager = context.getSystemService(
Context.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()
}
}
override fun onDetachedFromEngine(
binding: FlutterPlugin.FlutterPluginBinding
) {
channel.setMethodCallHandler(null)
}
}The when expression dispatches each method name. Every call must produce exactly one response:
result.success(value)returns a value to Dart.result.error(code, message, details)creates aPlatformException.result.notImplemented()tells Dart that the method is unsupported.
The Android implementation returns an Int, which the standard channel codec converts to a Dart int. The Dart API should therefore request the same type.
Lifecycle and common errors
Remove the handler in onDetachedFromEngine. This prevents calls from reaching an invalid plugin instance and releases the channel's reference to the handler.
Common mistakes include these:
- Using
"BatteryInfo"in Kotlin while Dart uses"battery_info". - Returning a string when Dart expects an integer.
- Forgetting
result.notImplemented()for unknown methods. - Keeping an
Activityreference in a long-lived plugin. - Calling
resultmore than once for one method call.
For simple system queries, this implementation is sufficient. Longer native operations should be moved away from the main thread and should still deliver their final result exactly once.
Exercise
What happens in Dart when the Kotlin code calls result.error("UNAVAILABLE", "Battery level not available.", null)?
Show answer
The channel reports a PlatformException. The Dart API can catch it and convert it into a plugin-specific exception.