Sub topic 1
How Platform Channels Work and Where They Break
Flutter runs Dart code in a cross-platform engine. Device features, such as sensors, files, Bluetooth, and battery information, often require Android or iOS APIs. A platform channel is a communication path between Dart and native code.
The channel sends messages through the Flutter engine. Dart sends a method name and arguments. Native code receives them, performs work, and returns a result or an error.
Prerequisites
This chapter assumes that you know basic Flutter app structure, Dart classes, async and await, and the purpose of Android and iOS native code. You should also know that Flutter plugins commonly use platform channels to expose device features.
The message flow
A common channel type is MethodChannel. Dart invokes a named method, and native code handles that name.
import 'package:flutter/services.dart';
class BatteryService {
static const _channel = MethodChannel('example.com/battery');
Future<int> getBatteryLevel() async {
final result = await _channel.invokeMethod<int>('getBatteryLevel');
if (result == null) {
throw StateError('The platform returned no battery level');
}
return result;
}
}The string example.com/battery identifies the channel. The string getBatteryLevel identifies the operation. Both sides must use exactly the same values.
On Android, a handler might look like this:
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"example.com/battery"
).setMethodCallHandler { call, result ->
when (call.method) {
"getBatteryLevel" -> {
val manager = getSystemService(BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(
BatteryManager.BATTERY_PROPERTY_CAPACITY
)
result.success(level)
}
else -> result.notImplemented()
}
}The Dart call returns a Future<int>, because communication crosses an engine boundary and native work may take time. The native handler must call exactly one result method: success, error, or notImplemented.
flowchart TD
A[Dart invokes method] --> B[Flutter engine encodes message]
B --> C[Native channel handler]
C --> D[Native API performs work]
D --> E[Native result is encoded]
E --> F[Dart Future completes or throws]caption: A MethodChannel request and response alt: A flowchart showing Dart sending a method through the Flutter engine to native code and receiving a result or error
Where string-based channels break
The compiler cannot check the agreement between the two sides. Several mistakes therefore appear only when the app runs.
| Problem | Typical result |
|---|---|
| Different channel names | The handler is never reached |
| Misspelled method name | `notImplemented` or an exception |
| Wrong argument key or type | A cast error or rejected call |
| Changed return shape | A runtime decoding error |
| Missing null handling | An unexpected null exception |
For example, Dart may expect an integer while native code returns a string. The code can compile on both sides because the channel carries dynamic message data. The failure occurs when Dart decodes the response.
Arguments have the same weakness:
final result = await _channel.invokeMethod<int>(
'getBatteryLevel',
{'includeHealth': true},
);The native implementation must know that the argument is named includeHealth and that it is a Boolean. Nothing in this Dart call verifies that a native handler reads the same key.
Why Pigeon helps
Pigeon is a code generator that places the channel contract in one typed Dart schema. It generates matching Dart, Kotlin, and Swift interfaces. Generated code replaces channel names, method-name strings, manual argument maps, and many casts in application code.
Pigeon does not remove the platform boundary. Native APIs can still fail, generated code can still become stale, and platform-specific behavior still needs testing. It reduces a particular class of coordination errors by making the message shape explicit and generating both sides from it.
Exercise
Exercise
Why can a misspelled MethodChannel method name compile successfully but fail at runtime?
Show answer
The method name is a string, so the Dart and native compilers do not verify that both sides use the same value. The native handler receives an unknown method and usually returns notImplemented.