Before writing a platform channel, search pub.dev. On 2026-11-08 the registry contains 94,898 published packages - a measured number, the command is at the bottom - and the probability that the native API you need is already wrapped is high. Channels are written for what is left: a proprietary SDK, a very specific API, native code your company already has.
When you really need them, the mechanism is simple to describe and easy to get wrong: a channel is identified by a string, the data is serialized, and the two sides must agree on that name and on those types. No compiler checks you. This article shows the two channels you will use, where they break, and the tool that puts type checking back in its place.
What was verified and what was not
The Dart code in this article was analyzed in a real Flutter project:
flutter analyze on Flutter 3.44.2 stable (revision
c9a6c48423) answers "No issues found!".
The Kotlin and Swift code was not compiled: compiling it requires the Android SDK and Xcode, which are not on this machine. It is written against the signatures in the official platform channel documentation, but treat it as something to verify in your own project, not as executed. The pub.dev package count, on the other hand, is measured.
The mental model: two ends and a string
A channel is a pipe with a name. On one side Dart, on the other the platform code; in between, a codec that turns values into bytes and back. The name of the channel is a string, and by convention you use an identifier with dots, like a Java package, so as not to collide with other plugins.
The types that pass through are not yours: they are a restricted set that the standard codec knows how to translate - numbers, strings, booleans, and lists and maps of these. An object of your own in Dart does not cross the pipe: you take it apart into a map, and on the other side you put it back together. This is where the fragility of the mechanism comes from, because the name of a key written in two different files is checked by no one.
The three channels, and which one you need
MethodChannel- you call a method and wait for a result: one question, one answerEventChannel- the native side emits values over time and Dart listens to them as aStreamBasicMessageChannel- free-form messages in both directions, without the concept of a "method"
The criterion that separates them is the shape of the conversation, not its complexity: if the question starts from Dart and has a single answer, the first; if the data arrives when it wants to - a sensor, the position, the Bluetooth state - the second. The third is the one you will use least, and it is worth knowing so as not to mistake it for the "generic" and therefore better choice: without the question-answer structure you have to handle the correlation between sending and return yourself.
MethodChannel: one question, one answer
The Dart side is a thin class that hides the channel. It is worth writing it always, even for a single method, because it concentrates in one place the channel string and the method names - that is, the things that can diverge from the native side.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class SensoreProssimita {
static const _canale = MethodChannel('com.example.proximity');
static Future<bool> disponibile() async {
try {
// invokeMethod<T> types the return value: no manual cast
final esito = await _canale.invokeMethod<bool>('isAvailable');
return esito ?? false;
} on MissingPluginException {
// The native side has not registered the channel: not present on this platform
return false;
} on PlatformException catch (e) {
debugPrint('proximity not available: ${e.code} ${e.message}');
return false;
}
}
static Future<double?> leggiDistanza() async {
try {
return await _canale.invokeMethod<double>('read');
} on PlatformException catch (e) {
debugPrint('read failed: ${e.code}');
return null;
}
}
}
The line to imitate is invokeMethod<bool> with the type in angle brackets.
Without it the method returns dynamic and the type error shows up at runtime, far from
the cause; with the type parameter, the check happens at the boundary and the signature of your
method is honest. Note the ?? false: the return is nullable anyway, because
the native side might send nothing.
The two catch clauses intercept two different failures, and telling them apart is the
part that pays off. PlatformException means the native side received the call and
answered with an error: there is a code that you chose on the other side.
MissingPluginException means that nobody answered, because the
channel is not registered on this platform.
The difference is practical: the first is a sensor error, the second is an error of yours - or the
normal condition on a platform you have not implemented. That is why here
MissingPluginException returns false silently: on desktop or web, "the
proximity sensor is not available" is the correct answer, not a failure.
If you remove the try blocks entirely, the code compiles and works as long as
everything goes well. Then, on the first device without that sensor, the exception climbs up to
build and the screen turns red. A platform channel is a system boundary, and like every
boundary it has to be guarded.
The Android side, in Kotlin
package com.example.proximity
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class ProximityPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
private lateinit var channel: MethodChannel
private lateinit var context: Context
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
// The string MUST match the one on the Dart side
channel = MethodChannel(binding.binaryMessenger, "com.example.proximity")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
val manager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val sensore = manager.getDefaultSensor(Sensor.TYPE_PROXIMITY)
when (call.method) {
"isAvailable" -> result.success(sensore != null)
"read" -> if (sensore == null) {
// code, message, details: the `code` arrives in PlatformException.code
result.error("NO_SENSOR", "No proximity sensor", null)
} else {
result.success(sensore.maximumRange.toDouble())
}
// Without this branch, Dart would receive MissingPluginException
else -> result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null) // without this, the plugin stays hanging around
}
}
The lines that matter are four. The string "com.example.proximity" must be
identical to the Dart one: one different letter and the call finds nobody, and the
symptom is a MissingPluginException that will make you look in the wrong place.
result.error("NO_SENSOR", ...) is what becomes PlatformException.code on
the other side, so that code is a public interface and must be chosen with the same care as a
method name.
result.notImplemented() in the else branch handles the case of the method
that Dart calls and the native side does not know - typically after you have added a method on one
side and not on the other. Omit it, and onMethodCall ends without calling any method
of result, and the Future in Dart never completes: the
worst bug of all, because there is no error, only an endless wait.
The general rule is this: every path of onMethodCall must call exactly once
success, error or notImplemented. Zero times means a hanging
Future, twice raises an exception on the native side.
Finally setMethodCallHandler(null) in onDetachedFromEngine: the channel
holds a reference to your plugin, which holds a reference to the context. Without that line, the
plugin outlives the Flutter engine that created it, and it is a memory leak that shows up only in
long sessions.
The iOS side, in Swift
import Flutter
import UIKit
public class ProximityPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(
name: "com.example.proximity", // the same string, again
binaryMessenger: registrar.messenger()
)
registrar.addMethodCallDelegate(ProximityPlugin(), channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let device = UIDevice.current
switch call.method {
case "isAvailable":
device.isProximityMonitoringEnabled = true
result(device.isProximityMonitoringEnabled)
device.isProximityMonitoringEnabled = false
case "read":
// iOS exposes a "near/far" boolean, not a distance
result(FlutterError(code: "NOT_SUPPORTED",
message: "iOS does not expose the distance",
details: nil))
default:
result(FlutterMethodNotImplemented)
}
}
}
The structure mirrors the Kotlin, with three differences of name: result is a
closure that you call instead of an object with methods, the error is built with
FlutterError, and the unhandled case is signalled by passing the constant
FlutterMethodNotImplemented. The single-call rule holds identically.
The "read" branch says something that matters more than the code: on iOS the proximity
sensor exposes only "near or far", not a distance. The two platforms do not offer
the same capability, and this is the normal case, not the exception.
The design consequence is that the Dart interface must be designed on the lowest common
denominator, or must explicitly allow "not supported here" - as the nullable double?
of leggiDistanza does. Promising on both platforms an API that only one can keep is
the quickest way to accumulate platform-specific branches inside the Dart code.
EventChannel: when the data arrives when it wants to
A sensor does not answer questions: it emits. Calling invokeMethod in a loop to read a
value twenty times a second is possible and wrong - twenty crossings of the boundary per second,
each with its own serialization. The EventChannel opens the pipe once.
Stream
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FlussoProssimita {
static const _canale = EventChannel('com.example.proximity/stream');
static Stream<double> get valori => _canale
.receiveBroadcastStream()
.map((e) => (e as num).toDouble())
.handleError((Object e) => debugPrint('error from the native side: $e'));
}
class SpiaProssimita extends StatelessWidget {
const SpiaProssimita({super.key});
@override
Widget build(BuildContext context) {
return StreamBuilder<double>(
stream: FlussoProssimita.valori,
builder: (context, snap) {
if (snap.hasError) return const Text('sensor unreachable');
if (!snap.hasData) return const CircularProgressIndicator();
return Text('${snap.data!.toStringAsFixed(1)} cm');
},
);
}
}
(e as num).toDouble() is not pedantry. The standard codec sends an integer as an
int and a decimal as a double: if the native side emits the value 0 and
you write e as double, you get a cast error on that single value, while all the others
go through. The cast to num followed by toDouble() accepts both.
receiveBroadcastStream() must be called with care: it returns a broadcast
stream, and the native side is told to start emitting at the first listener and to stop when the
last one unsubscribes. Written as a get, as here, every access to the property creates
a new stream: in this example it is fine because StreamBuilder reads it once, but using
it in a build that repeats would reopen the channel on every frame.
In the StreamBuilder the order of the three checks is significant:
hasError before hasData, because a snapshot can have an old datum
and a new error, and in that case you want to show the error. Invert them, and you would
keep showing the last good value while the sensor has already gone silent.
On the native side this channel corresponds to a StreamHandler with two methods,
onListen and onCancel. The second is the one people forget: if you do not
unsubscribe the sensor listener in onCancel, the sensor stays active after the user has
left the screen, and that is battery drain that the user will attribute to your app.
Pigeon: getting the strings out of the way
Everything above has a structural flaw: the channel name, the method names and the shape of the data are written two or three times, in different languages, and no compiler compares them. Pigeon is the official tool that solves this: you declare the interface once in Dart and it generates the code for the three sides.
import 'package:pigeon/pigeon.dart';
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/proximity_api.g.dart',
kotlinOut: 'android/src/main/kotlin/com/example/ProximityApi.g.kt',
swiftOut: 'ios/Classes/ProximityApi.g.swift',
))
// A data class: it becomes a Kotlin data class and a Swift struct
class ProximityInfo {
ProximityInfo({required this.distance, required this.isNear});
final double? distance; // null where the platform does not expose it
final bool isNear;
}
// HostApi: implemented by the native side, called from Dart
@HostApi()
abstract class ProximityHostApi {
bool isAvailable();
ProximityInfo read();
}
// FlutterApi: implemented by Dart, called from the native side
@FlutterApi()
abstract class ProximityFlutterApi {
void onProximityChanged(ProximityInfo info);
}
The gain is that the strings disappear. After dart run pigeon --input
pigeons/proximity.dart, you call a typed Dart method and implement a Kotlin or Swift
interface: if you add a method to the interface and do not implement it on the native side, it does
not compile. The error moves from runtime to compile time, which is the whole point.
The two annotations are to be read as the two directions of the pipe. @HostApi()
declares what the native side offers and Dart consumes - it replaces the
MethodChannel. @FlutterApi() is the opposite direction: methods that
Dart implements and the native side calls, and it is the typed way of doing what the
EventChannel does with a stream.
The nullable double? of distance is the same design decision as before,
now made explicit in the contract: the type says that datum can be missing, and the generated code
propagates it on both platforms. That is why it pays to move to Pigeon early, on a plugin you expect
to maintain: not because it writes less code, but because the contract becomes a file that breaks
when you get it wrong.
Deciding whether to write a channel
In order
- Search pub.dev: 94,898 published packages as of 2026-11-08
- If you find a plugin, check when it was last updated and which platforms it declares
- Write a channel for proprietary SDKs, very specific APIs, native code you already have
- If you will maintain the plugin over time, start directly from Pigeon
- Design the Dart interface on the lowest common denominator between platforms, or admit "not supported"
The order is the only thing that matters in this list: the first two items exist to avoid the other three, and skipping them is the most common way of spending a week on a problem already solved. The second is the one skipped most often, and the one worth the most: a plugin that exists but has not been updated for years and does not declare your platform is a debt, not a solution. The last item is not about time but about correctness, and it is the one that determines how much platform-specific code will end up in your Dart.
What you can do now
You know when a channel is needed and when it is not, how to tell PlatformException
from MissingPluginException and why the difference matters, how to respect the
single-call rule on result, how to choose EventChannel when the data
arrives on its own, and how to move the contract into Pigeon when the strings become too many.
Crossing the boundary costs, so the next step is knowing how much: how to measure whether a native call is eating the frame budget is in Impeller, the rendering pipeline and jank. On the testing front, a channel must be replaced with a double so that you can test the Dart without a device, and the way to do it is in widget testing and golden tests. Where to place this code so that it does not spread across the whole app is a matter of structure, covered in feature-first architecture. And if your channel feeds an animation, the right level at which to consume it is discussed in implicit animations, physics and custom painters. On desktop the direct route, without channels, goes through FFI and is in Flutter Desktop.
Sources
- Flutter - Writing platform-specific code - the architecture of the channels, the types the standard codec supports, and the signatures of the Kotlin and Swift sides used in the examples. Consulted on 2026-11-08.
-
Flutter API -
MethodChannel-invokeMethod<T>, the nullable return, and the distinction betweenPlatformExceptionandMissingPluginException. Consulted on 2026-11-08. -
Flutter API -
EventChannel- the semantics ofreceiveBroadcastStreamand theonListen/onCancelcycle on the native side. Consulted on 2026-11-08. -
pub.dev -
pigeonpackage - the@HostApiand@FlutterApiannotations, the generation options and the run command. Consulted on 2026-11-08. -
Measurement of pub.dev packages - 94,898 names, obtained with
curl --compressed https://pub.dev/api/package-namesand counting thepackageslist in the response, on 2026-11-08. The endpoint requires accepting gzip compression, otherwise it answers 406. The value "over 40,000" that appeared in the previous version of this article was an underestimate of more than half. -
Code verification - the Dart blocks analyzed with
flutter analyzeon Flutter 3.44.2 stable (revisionc9a6c48423) on 2026-11-08, result "No issues found!". Kotlin and Swift not compiled: the native build chain is missing.
The first four entries are project documentation, and it is the only sensible source for the names of the native classes, which change between versions of the Android embedding. The last two have a different function: they say which statements of this article rest on a measurement and which on a reading. The distinction is why the pub.dev count reports the command instead of the number alone - so that in six months, when the number has changed, you will know how to redo it.
Commenti
Caricamento commenti...
Sign in to comment