Sub topic 2
Implementing the Android Side in Kotlin
This chapter assumes you can write Dart and build Flutter apps, have basic Kotlin and Swift reading skills, and have Android Studio, Xcode, and a working Flutter toolchain installed. You should also know the basics of Gradle and CocoaPods.
A plugin's native code runs on each platform and answers calls sent from Dart. On Android, the native code is a Kotlin class. Flutter creates that class when the app starts, and it attaches the class to a MethodChannel, a named pipe that carries method calls between Dart and native code.
Writing the Android plugin class
The Android class implements FlutterPlugin so Flutter can attach and detach it, and MethodCallHandler so it can answer calls.
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 channel name "battery_info" must match the name used in Dart and in Swift. Flutter checks the name only at runtime, so a typo fails silently and the call never arrives.
Implementing the iOS side in Swift
The iOS class follows the same pattern. It registers the same channel name and answers the same method.
import Flutter
import UIKit
public class BatteryInfoPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "battery_info", binaryMessenger: registrar.messenger())
let instance = BatteryInfoPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getBatteryLevel":
UIDevice.current.isBatteryMonitoringEnabled = true
let level = UIDevice.current.batteryLevel
if level < 0 {
result(FlutterError(code: "UNAVAILABLE", message: "Battery level not available.", details: nil))
} else {
result(Int(level * 100))
}
default:
result(FlutterMethodNotImplemented)
}
}
}Reporting errors from native code to Dart
When native code calls result.error or FlutterError, Dart receives a PlatformException with the same code and message. The Dart wrapper converts it into a plugin-specific exception so callers do not depend on Flutter's internal types.
class BatteryInfoException implements Exception {
BatteryInfoException(this.code, this.message);
final String code;
final String? message;
}Use result.notImplemented() on Android and FlutterMethodNotImplemented on iOS for unknown methods. Dart then receives a MissingPluginException, which signals a mismatch between the Dart and native code.
> Note: Callbacks to result must run on the platform's main thread. Use a background thread only for slow work, and post the result back to the main thread.
Running the plugin from the example app
Generate the project and run its example app on a connected device:
flutter create --template=plugin --platforms=android,ios -a kotlin -i swift --org com.example battery_info
cd battery_info/example
flutter runThe example app is the fastest way to check that both native classes register. Call getBatteryLevel from a button and confirm that the value appears. If you see MissingPluginException, check the pluginClass entries in pubspec.yaml.
Exercise
The Kotlin handler returns result.error("UNAVAILABLE", ...) when the battery level is negative. What does the Dart caller receive, and which field of the exception holds the "UNAVAILABLE" text?
Show answer
The Dart caller receives a PlatformException. The "UNAVAILABLE" text is stored in its code field, and the message text is in its message field.