Sub topic 1
How platform channels work and where they break
Flutter apps sometimes need to call code that runs outside Dart. Examples are reading the battery level, opening a system dialog, or using a vendor SDK that exists only in Kotlin or Swift. Platform channels are Flutter's built-in way to do this. This chapter explains how they work, shows a complete hand-written example, and lists the specific ways that approach fails. The rest of the tutorial builds on those failure points.
Prerequisites
This chapter assumes you have:
- Basic Dart and Flutter app structure: a
pubspec.yaml, alib/folder, and theandroid/andios/host projects. - Familiarity with
async/awaitandFuturein Dart. - Reading knowledge of Kotlin or Swift. You do not need to write either from scratch.
You do not need any prior experience with platform channels or Pigeon.
The working model
A Flutter app runs Dart code inside an engine that is embedded in a native host app. The Dart side and the native side live in the same process, but they do not share objects or memory. They exchange messages instead.
A platform channel is a named pipe for those messages. Three parts make one work:
- A binary messenger moves raw bytes between Dart and the native side.
- A codec converts values to bytes and back. The default is the
StandardMethodCodec, which uses theStandardMessageCodecfor the values. - A channel name, a plain string such as
com.example.app/battery. Both sides must use the same string to find each other.
The most common channel type is MethodChannel. Dart calls invokeMethod with a method name (a string) and optional arguments. The native handler receives a call object, does the work, and answers with a success value, an error, or "not implemented".
Three details of this model matter later.
- Calls are asynchronous.
invokeMethodalways returns aFuture, even if the native work is instant. - Values are copied, not shared. Whatever you send is serialized and rebuilt on the other side, so only types the codec knows can cross.
- The handler is registered by name at startup. Dart does not check that a handler exists at compile time. It finds out when the call runs.
A complete hand-written example
The example reads the battery level. It has three parts, and all of them must agree on the strings and types.
The Dart side
import 'package:flutter/services.dart';
class BatteryService {
static const MethodChannel _channel =
MethodChannel('com.example.app/battery');
Future<int?> getBatteryLevel() async {
final int? level = await _channel.invokeMethod<int>('getBatteryLevel');
return level;
}
}The type argument <int> is not enforced by the channel. It only tells Dart what to cast the decoded result to. If native code sends something else, the cast fails at runtime.
The Android side
This goes in MainActivity.kt:
package com.example.app
import android.content.Context
import android.os.BatteryManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"com.example.app/battery"
).setMethodCallHandler { call, result ->
when (call.method) {
"getBatteryLevel" -> {
val manager =
getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(
BatteryManager.BATTERY_PROPERTY_CAPACITY
)
result.success(level)
}
else -> result.notImplemented()
}
}
}
}The iOS side
This goes in AppDelegate.swift:
import Flutter
import UIKit
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller = window?.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(
name: "com.example.app/battery",
binaryMessenger: controller.binaryMessenger
)
channel.setMethodCallHandler { call, result in
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)
}
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}Count the strings that must match across the three files: the channel name appears three times and the method name appears three times. The compiler checks none of them.
What the codec can carry
The standard codec supports a fixed set of types. Each Dart type maps to a platform type like this:
| Dart | Kotlin | Swift |
|---|---|---|
| `null` | `null` | `nil` |
| `bool` | `Boolean` | `NSNumber(value: Bool)` |
| `int` | `Int` or `Long` | `NSNumber(value: Int32)` or `NSNumber(value: Int64)` |
| `double` | `Double` | `NSNumber(value: Double)` |
| `String` | `String` | `String` |
| `Uint8List` | `ByteArray` | `FlutterStandardTypedData` |
| `List` | `List` | `Array` |
| `Map` | `HashMap` | `Dictionary` |
Two rows deserve attention. A Dart int is 64 bits wide, but on Android it arrives as Int when the value fits in 32 bits and as Long otherwise. Code that casts to Long works for large values and throws for small ones. Also, List and Map are untyped containers, so a List<String> on the Dart side arrives as a list of unknown element type.
There is no way to send your own class. To pass a BatteryInfo with a level and a state, you must flatten it into a Map or List on one side and rebuild it on the other.
Where it breaks
Every failure below comes from the same cause: the contract between the two sides lives in strings and unchecked casts, not in types. Most of these failures appear at runtime, and some appear only on one platform.
Typos in names
If the Dart channel is com.example.app/batery, nothing fails to compile. At runtime, Dart throws a MissingPluginException because no handler is registered on that name. The same exception appears if the channel name is right but the method name is wrong, because the handler falls into notImplemented().
import 'package:flutter/services.dart';
Future<void> demonstrateMissingHandler() async {
const channel = MethodChannel('com.example.app/battery');
try {
await channel.invokeMethod<int>('getBatteryLevell'); // typo
} on MissingPluginException catch (e) {
print('No handler: ${e.message}');
}
}The same exception also appears when the native handler was never registered, for example because configureFlutterEngine was not called on a secondary engine. The message does not tell you which of these causes applies.
Argument shape drift
Arguments travel as one Object?, usually a Map. Suppose Dart sends {'unit': 'percent'} and Kotlin reads call.argument<String>("units"). The key does not match, so Kotlin gets null and may carry on with a wrong default. Nothing reports the mismatch.
Casts fail more loudly but still late. If Kotlin expects Int and Dart sends 5000000000, the value arrives as Long and the cast throws a ClassCastException on Android only.
Return type drift
If a developer changes the Kotlin handler to return a Map and forgets Dart, invokeMethod<int> throws a TypeError when it casts the result. If Swift returns Int and Kotlin returns String for the same method, the app works on one platform and breaks on the other. Two hand-written native files can diverge, and nothing compares them.
Nullability is not carried across
The codec transports null, but it has no way to say "this value is never null". The Dart signature Future<int?> is a promise you make by hand. If the native side returns null and your Dart code assumed int, you find out at runtime.
Result handling errors
On the native side, each call must be answered exactly once. Two mistakes are common:
- Never calling
result. The DartFuturethen never completes, and the UI waits forever. - Calling
resulttwice. Android logs an error, and iOS can crash.
Errors lose structure
Native errors arrive in Dart as a PlatformException with three fields: code, message and details. The code is a free-form string that both sides must agree on by convention. Dart code that wants to react to a specific failure ends up comparing strings:
import 'package:flutter/services.dart';
Future<int> readLevelOrDefault(MethodChannel channel) async {
try {
final level = await channel.invokeMethod<int>('getBatteryLevel');
return level ?? -1;
} on PlatformException catch (e) {
if (e.code == 'UNAVAILABLE') {
return -1;
}
rethrow;
}
}If Kotlin spells the code UNAVAILABLE and Swift spells it Unavailable, this check works on one platform only.
Threading assumptions
On Android, a MethodChannel handler runs on the platform's main (UI) thread by default. The same is true on iOS. Slow work inside the handler, such as reading a large file, blocks the native UI thread and can freeze gestures and animations. The Dart side stays responsive, so the problem is easy to misread as a Flutter performance issue. Moving the work to a background thread means you must still deliver result correctly from that thread, and the rules for doing so are different on each platform. Later chapters cover this.
Refactoring and review cost
Because the contract is spread across three files in three languages, renaming a method means a search-and-replace across all of them. Adding a field to a request means editing Dart map construction, a Kotlin argument call, and a Swift dictionary read. In code review, a reviewer sees three small diffs and has to check by eye that they agree.
Summary of failure modes
| Failure | When it surfaces | Typical symptom |
|---|---|---|
| Wrong channel or method name | First call at runtime | `MissingPluginException` |
| Wrong argument key | At runtime, often silently | `null` or default value used |
| Integer width mismatch | Runtime, one platform | `ClassCastException` on Android |
| Return type mismatch | Runtime | `TypeError` in Dart |
| Missing `result` call | Runtime | `Future` never completes |
| Mismatched error codes | Runtime | Error handling works on one platform |
| Slow work in handler | Under load | UI jank on native side |
What this means for the next chapters
The failures above share a pattern. A single description of the API (names, argument types, return types, nullability) exists only in the developer's head and is copied by hand into three places. The remaining chapters of this tutorial show how a code generator turns that description into one written source, so the compiler can check the copies against each other. Your job in this chapter is only to recognize the problem. You should be able to look at a MethodChannel call and name what could go wrong with it.
Exercise
A Dart call invokeMethod<int>('getBatteryLevel') throws a MissingPluginException on Android, but the same call works on iOS. Name two causes you would check, and explain why the compiler could not have caught either.
Show answer
Check (1) that the Android channel name string exactly matches the Dart one, and that the method name in the when branch is spelled getBatteryLevel, because a mismatched method falls into notImplemented(); and (2) that configureFlutterEngine registers the handler on the engine actually running the Dart code, for example when a cached or secondary engine is used. The compiler could not catch either one because channel and method names are plain strings and handler registration happens at runtime, so the Dart, Kotlin and Swift files never check against each other.
Exercise
Dart sends the integer 5000000000 over a MethodChannel, and the Kotlin handler reads it with call.argument<Int>("size"). What happens, and what would happen with the value 42?
Show answer
The value 5000000000 does not fit in 32 bits, so the standard codec delivers it as a Kotlin Long, and reading it as Int throws a ClassCastException. The value 42 fits in 32 bits, so it arrives as an Int and the same code works. This is why integer handling can pass in testing with small values and fail in production with large ones.
Exercise
A Swift handler has a code path with no call to result. What does the Dart caller observe?
Show answer
Nothing is thrown. The Future returned by invokeMethod never completes, so any code awaiting it hangs, and the UI usually shows an endless loading state. Every path through a handler must call result exactly once.