Sub topic 4
How platform channels pass messages
This chapter assumes that you can write asynchronous Dart code with Future, and that you know the basic structure of a Flutter plugin. You should also be able to read simple Kotlin and Swift. The examples use a MethodChannel to send one request from Dart to native code and receive one response.
The message path
A platform channel is a named communication path between Dart and native code. Dart sends a message through the channel. Flutter serializes the message, delivers it to Android or iOS, and serializes the native response back to Dart.
A MethodChannel carries a method name and optional arguments. The native side examines the method name and completes the request with a result, an error, or a “not implemented” response.
The channel name is part of the contract. Both sides must use the exact same string. Method names and argument shapes are also part of the contract.
| Contract item | Example | Requirement |
|---|---|---|
| Channel name | `battery_info` | Must match on both sides |
| Method name | `getBatteryLevel` | Native code must recognize it |
| Arguments | `{ "unit": "percent" }` | Must use a supported value shape |
| Result | `42` | Dart must expect the returned type |
The standard message codec
Flutter's standard codec converts common Dart values into values that Kotlin and Swift can read. Supported values include:
null- Boolean values
- Integers and floating-point numbers
- Strings
- Lists
- Maps with supported keys and values
- Byte arrays, represented by typed data in Dart
The codec does not send arbitrary Dart objects. Convert domain objects to maps or lists before calling the channel, then reconstruct them after receiving the response. The codec is also not automatically JSON. Do not assume that JSON encoding rules apply to every value.
Calling a method from Dart
Keep channel details inside the plugin's public API. Callers should use a meaningful Dart method instead of knowing the channel name or native method string.
import 'package:flutter/services.dart';
class BatteryInfo {
static const MethodChannel _channel = MethodChannel('battery_info');
Future<int> getBatteryLevel() async {
final int? level = await _channel.invokeMethod<int>(
'getBatteryLevel',
<String, Object?>{'unit': 'percent'},
);
if (level == null) {
throw StateError('The platform returned no battery level.');
}
return level;
}
}invokeMethod<int> asks Flutter to decode the result as an integer. The call returns a Future because native code may need time to read a system service or perform other work.
Handling the call on Android
The Android handler receives a MethodCall. It must complete the supplied Result exactly once. Returning success sends a value to Dart. Returning error sends a structured platform error. Returning notImplemented tells Dart that the method is unavailable.
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"getBatteryLevel" -> {
val unit = call.argument<String>("unit")
if (unit != "percent") {
result.error("INVALID_ARGUMENT", "Unsupported unit.", null)
return
}
result.success(42)
}
else -> result.notImplemented()
}
}The iOS handler follows the same contract. It uses FlutterMethodCall to read the method and arguments, then calls the supplied FlutterResult.
Choosing a channel type
Use the channel that matches the communication pattern:
MethodChannelis for request-and-response operations.EventChannelis for a stream of native events, such as sensor updates.BasicMessageChannelis for ongoing messages where you define the message format yourself.
Start with MethodChannel when each Dart call should produce one native response. Use EventChannel when the native side produces multiple values over time.
Exercise
What happens if Dart calls getBatteryLevel on a channel named battery_info, but the native code listens on battery_status?
Show answer
The native handler does not receive the call. The channel names must match exactly, so Dart receives a missing or unhandled channel error instead of the intended result.