Sub topic 4
How platform channels pass messages
This chapter assumes you can write Dart and read basic Kotlin and Swift. It also assumes you have generated a plugin project, as in the earlier chapters. By the end you should be able to describe what happens between invokeMethod in Dart and result.success in native code. You should also be able to predict which values survive the trip and which ones arrive as a surprise.
The model: named channels over a binary messenger
Dart code and native code run in different runtimes. They cannot share objects or call each other directly. Flutter connects them with messages, which are byte buffers sent asynchronously through the engine.
Three layers are involved:
- Channel. A named endpoint.
MethodChannel('battery_info')in Dart pairs with aMethodChannelof the same name on Android and iOS. - Codec. A pair of functions that turn values into bytes and bytes back into values.
- Binary messenger. The engine object that delivers the bytes to whichever handler is registered under that name.
Every call is a request followed by exactly one reply. The Dart side sees that reply as a Future. Nothing blocks the Dart isolate while native code works.
Channel names are the only contract
The channel name is a plain string. The engine does not check it against anything. If Dart sends to "battery_info" and no native handler is registered under that name, the call fails at run time with a MissingPluginException. A misspelling on one side produces the same failure.
Two conventions keep names safe:
- Use a name based on the package, such as
battery_info. Use a path-like name for secondary channels, such asbattery_info/level_changes. - Define the name once per language and reuse the constant. The Dart class from the spine does this with a private static field.
A registered handler also replaces any earlier handler on the same name. Two plugins using one name will silently collide, so make the name specific.
The standard message codec
MethodChannel uses StandardMethodCodec by default, and that codec uses StandardMessageCodec for the values. It supports a fixed set of types. Anything else fails with an encoding error.
| Dart | Android (Kotlin) | iOS (Swift) |
|---|---|---|
| `null` | `null` | `nil` |
| `bool` | `Boolean` | `NSNumber` holding a Bool |
| `int` (fits 32 bits) | `Int` | `NSNumber` holding an Int |
| `int` (needs 64 bits) | `Long` | `NSNumber` holding an Int |
| `double` | `Double` | `NSNumber` holding a Double |
| `String` | `String` | `String` |
| `Uint8List` | `ByteArray` | `FlutterStandardTypedData` |
| `Int32List`, `Int64List`, `Float64List` | `IntArray`, `LongArray`, `DoubleArray` | `FlutterStandardTypedData` |
| `List` | `List` (an `ArrayList`) | `Array` |
| `Map` | `Map` (a `HashMap`) | `Dictionary` |
Gotchas in the type mapping
- Integer width depends on the value. A Dart
intthat fits in 32 bits arrives in Kotlin asInt. A larger one arrives asLong. Casting a received value withas Longcan throwClassCastExceptionfor small numbers. Read numeric arguments asNumberand convert them if width matters. - Collections are untyped. A Dart
List<int>arrives as a list ofAny?. Check and cast each element on the native side. - Custom classes are not supported. Send a
Mapor a list, and rebuild the object on the other side. Pigeon, covered in a later chapter, automates this. - Results come back as
Object?.invokeMethod<int>casts the result for you, but it throws aTypeErrorif the native side sent another type.
Sending arguments
invokeMethod takes a method name and one optional argument. When you need several values, pass a Map. The following Dart class is complete and can be added to the plugin. It uses a hypothetical setLowBatteryThreshold method.
import 'package:flutter/services.dart';
class BatteryThreshold {
static const MethodChannel _channel = MethodChannel('battery_info');
/// Asks the platform to remember a low-battery threshold from 1 to 100.
Future<bool> setLowBatteryThreshold(int percent) async {
final bool? stored = await _channel.invokeMethod<bool>(
'setLowBatteryThreshold',
<String, Object?>{'percent': percent},
);
return stored ?? false;
}
}The Android branch of onMethodCall reads that map with call.argument. It returns null when the key is missing or has another type. The following branch belongs inside the when (call.method) block of BatteryInfoPlugin.
"setLowBatteryThreshold" -> {
val percent = call.argument<Int>("percent")
if (percent == null || percent !in 1..100) {
result.error("INVALID_ARGUMENT", "percent must be an integer from 1 to 100.", null)
} else {
// Store the value here, for example in SharedPreferences.
result.success(true)
}
}On iOS, call.arguments has type Any?, so you cast it yourself. The branch below belongs inside the switch call.method block of handle.
case "setLowBatteryThreshold":
let args = call.arguments as? [String: Any]
if let percent = args?["percent"] as? Int, (1...100).contains(percent) {
// Store the value here, for example in UserDefaults.
result(true)
} else {
result(FlutterError(code: "INVALID_ARGUMENT",
message: "percent must be an integer from 1 to 100.",
details: nil))
}Validating on the native side is not optional. The channel enforces no schema, so a bad Dart caller or an older plugin version can send anything.
The three possible replies
A native handler must answer each call exactly once, with one of three outcomes:
| Outcome | Android | iOS | What Dart sees |
|---|---|---|---|
| Success | `result.success(value)` | `result(value)` | The `Future` completes with the value |
| Error | `result.error(code, message, details)` | `result(FlutterError(...))` | A `PlatformException` is thrown |
| Unknown method | `result.notImplemented()` | `result(FlutterMethodNotImplemented)` | A `MissingPluginException` is thrown |
Replying twice causes an error in the log on Android, and the second reply is ignored. Never replying leaves the Dart Future pending forever, which usually looks like a frozen screen. Check that every branch of your handler ends in a reply, including catch blocks.
Because both unknown methods and absent handlers raise MissingPluginException, the exception alone does not tell you which one happened. If the platform is Android or iOS and you registered the plugin, suspect a method name typo. If you see it after adding a plugin, do a full restart, because hot reload does not register new native code.
Threads and timing
The engine delivers channel calls to your handler on the platform's main thread (the UI thread on Android, the main queue on iOS). Short work is fine there. Anything slow, such as disk or network access, blocks the platform UI and causes dropped frames. A later chapter covers moving that work to a background thread. The reply can be sent from another thread on iOS, but Android requires result to be called on the main thread, so post back before replying.
On the Dart side, messages go through the root isolate by default. Calling a channel from a background isolate needs extra setup, which is beyond this chapter.
Exercise
A Dart caller sends invokeMethod('setLowBatteryThreshold', {'percent': 20}). Your Kotlin handler contains val percent = call.argument<Long>("percent") and always gets a failed cast or an unexpected result. Why, and what is a safe fix?
Show answer
The standard codec sends a Dart int that fits in 32 bits as a 32-bit integer, so Kotlin receives an Int, not a Long. Reading it as Long fails. Read the value as Number (for example call.argument<Number>("percent")?.toInt()) or as Int when the range is known to be small. Validate the result and reply with result.error if it is null or out of range.
Exercise
Your Dart code calls invokeMethod('getBatteryLevl'), a misspelled method name, on a plugin whose handlers are correctly registered. Which exception does Dart throw, and which native reply produced it?
Show answer
Dart throws MissingPluginException. The native when or switch falls into its default branch, which replies result.notImplemented() on Android or FlutterMethodNotImplemented on iOS.