Platform channels
Why it matters
- When Flutter needs an Android API that no plugin covers (a sensor, a vendor SDK, a system setting), it goes through a platform channel. Every Flutter plugin you depend on is built the same way.
- On Android, channel handlers run on the main thread by default. Doing disk or network work there blocks the UI and can cause ANRs, exactly as in a native Android app.
MethodChannel,EventChannel, and Pigeon are what interviewers ask about. Knowing when to use each, and how errors and threading work, separates someone who has only used plugins from someone who can write one.MissingPluginExceptionandPlatformExceptionare the two channel errors you will meet in practice; knowing what causes each saves hours of debugging.
The simple explanation
- Think of a platform channel as a named phone line between the Dart side and the Kotlin side.
- MethodChannel is a phone call: you ask one question and get one answer (or an error).
- EventChannel is a news feed: once you subscribe, the Android side keeps sending updates until you unsubscribe.
- Pigeon is a shared phrasebook: both sides are generated from one definition, so they cannot disagree on names or types.
- The codec is the translator: it only knows a fixed vocabulary of types, not arbitrary objects.
What is a platform channel in Flutter? It is a named, asynchronous message channel between Dart code and the host platform (Kotlin or Java on Android). Both sides create a channel with the same name string. Messages are encoded by a codec, passed through the engine's BinaryMessenger, and decoded on the other side.
| Channel | Direction | Typical use |
|---|---|---|
MethodChannel | Either side can call the other; one reply per call | One-shot calls: read a setting, start a native flow |
EventChannel | Native to Dart stream, started and stopped by the Dart listener | Continuous data: sensor readings, connectivity changes |
BasicMessageChannel | Either direction, plain messages with a chosen codec | Simple message passing without method names |
| Pigeon (code generator) | Generates typed APIs in both directions | Structured data and larger APIs where type safety matters |
Mechanism. Dart calls invokeMethod('name', args). StandardMethodCodec (built on StandardMessageCodec) encodes the arguments in a compact binary format. It supports null, bool, numbers, String, typed byte and number lists such as Uint8List, and List and Map of those. On Android the call reaches your MethodCallHandler on the main thread. You reply exactly once with result.success(value), result.error(code, message, details), or result.notImplemented(). On the Dart side, invokeMethod<T> returns a Future<T?>; an error becomes a PlatformException, and notImplemented becomes a MissingPluginException.
EventChannel uses receiveBroadcastStream() on the Dart side. The Android side implements EventChannel.StreamHandler: onListen runs when Dart starts listening and gives you an EventSink, and onCancel runs when the Dart subscription is cancelled. Start native work in onListen and stop it in onCancel.
Pigeon generates matching Dart and Kotlin (or Java, Swift, Objective-C, C++) code from an API defined in a Dart file, using @HostApi() for calls from Dart to native and @FlutterApi() for calls from native to Dart. You implement a generated Kotlin interface instead of switching on method-name strings.
Threading. Platform-side handlers run on the Android main (UI) thread unless you create the channel with a background TaskQueue from binaryMessenger.makeBackgroundTaskQueue(). Calls from native code into Dart must be made on the main thread.
Notes
MethodChannelis for request and reply,EventChannelfor native-to-Dart streams,BasicMessageChannelfor plain messages, and Pigeon for generated, type-safe APIs.invokeMethod<T>returnsFuture<T?>. The native side can reply withnull, so handle it.- In a custom app channel, register handlers in
FlutterActivity.configureFlutterEngine(flutterEngine)usingflutterEngine.dartExecutor.binaryMessenger. In a plugin, implementFlutterPluginand register inonAttachedToEngine, usingbinding.binaryMessenger. - Handlers run on the main thread. Move slow work off it (a coroutine with
withContext(Dispatchers.IO), or a backgroundTaskQueue), and reply when the work finishes. Every call must get exactly one reply. PlatformExceptionon the Dart side carries thecode,message, anddetailspassed toresult.error. Use stable error codes so Dart can branch on them.MissingPluginExceptionmeans no handler answered: a typo in the channel name, a handler not registered on the engine that runs this Dart code, a plugin added without a full rebuild (hot restart is not enough), or a method the handler markednotImplemented.StandardMessageCodeccannot send arbitrary objects. Convert to maps and lists, extendStandardMessageCodecwithwriteValueandreadValueOfTypefor custom types, or let Pigeon generate the codec.- Cancel the
StreamSubscriptionfromreceiveBroadcastStream()indispose(). That is what triggersonCancelon Android, where you unregister sensors and listeners. - Do not call
invokeMethodfrombuild(). Call it frominitState, a state holder (Provider, Riverpod, Bloc), or an event handler. - For synchronous calls into C or C++ libraries use
dart:ffi; for video or camera frames use aTexturewidget backed by a native surface. Channels are asynchronous and copy every message. - In tests, mock a channel with
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandlerso Dart logic can be tested without a device.
Code example
A thin Dart wrapper around a MethodChannel and an EventChannel, followed by the matching Kotlin side in MainActivity.
import 'package:flutter/services.dart';
/// Thin wrapper so the rest of the app never touches a raw channel.
class NativeBridge {
static const _method = MethodChannel('com.example/native_bridge');
static const _events = EventChannel('com.example/sensor_events');
// One-shot call. Do not call it from build().
Future<String> getDeviceId() async {
try {
final id = await _method.invokeMethod<String>('getDeviceId');
return id ?? 'unknown';
} on PlatformException catch (e) {
throw Exception('Native call failed (${e.code}): ${e.message}');
} on MissingPluginException {
throw Exception('No handler registered for com.example/native_bridge');
}
}
Future<String?> readConfig() =>
_method.invokeMethod<String>('readConfig');
// Continuous stream. The caller must cancel the subscription.
Stream<String> accelerometer() =>
_events.receiveBroadcastStream().cast<String>();
}import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.provider.Settings
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.io.IOException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainActivity : FlutterActivity() {
private val scope = MainScope()
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val messenger = flutterEngine.dartExecutor.binaryMessenger
MethodChannel(messenger, "com.example/native_bridge").setMethodCallHandler { call, result ->
// Runs on the main thread.
when (call.method) {
"getDeviceId" -> result.success(
Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
)
"readConfig" -> scope.launch {
try {
val text = withContext(Dispatchers.IO) {
File(filesDir, "config.json").readText()
}
result.success(text) // back on the main thread
} catch (e: IOException) {
result.error("IO_ERROR", e.message, null)
}
}
else -> result.notImplemented()
}
}
val sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
EventChannel(messenger, "com.example/sensor_events").setStreamHandler(
object : EventChannel.StreamHandler {
private var listener: SensorEventListener? = null
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
if (sensor == null) {
events.error("NO_SENSOR", "No accelerometer on this device", null)
return
}
val l = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
events.success("x=${event.values[0]}")
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
}
listener = l
sensorManager.registerListener(l, sensor, SensorManager.SENSOR_DELAY_UI)
}
override fun onCancel(arguments: Any?) {
listener?.let { sensorManager.unregisterListener(it) }
listener = null
}
}
)
}
override fun onDestroy() {
scope.cancel()
super.onDestroy()
}
}- The channel name strings must match exactly on both sides; a mismatch shows up on the Dart side as
MissingPluginException. readConfigdoes file I/O onDispatchers.IOand replies after switching back, so the main thread never blocks andresultis called on it.MainScopeneedskotlinx-coroutines-androidon the classpath.- Only
IOExceptionis caught, so coroutine cancellation still propagates normally. onCancelunregisters the sensor listener. It only runs if the Dart side cancels its subscription, which is whydispose()must callcancel().- With Pigeon, the
when (call.method)block disappears: you implement a generated interface and the generated code does the encoding and decoding.
Run the idea in plain Kotlin
// Models a method channel: Dart sends a named call, the native handler
// replies exactly once with success, error or notImplemented.
sealed interface Reply
data class Success(val value: Any?) : Reply
data class Error(val code: String, val message: String) : Reply
object NotImplemented : Reply
class MethodChannel(val name: String) {
private var handler: ((String, Map<String, Any?>) -> Reply)? = null
fun setMethodCallHandler(h: (String, Map<String, Any?>) -> Reply) { handler = h }
fun invokeMethod(method: String, args: Map<String, Any?> = emptyMap()): String {
val h = handler ?: return "MissingPluginException: no handler on " + name
return when (val reply = h(method, args)) {
is Success -> "Success: " + reply.value
is Error -> "PlatformException(" + reply.code + "): " + reply.message
NotImplemented -> "MissingPluginException: " + method + " not implemented"
}
}
}
fun main() {
val unregistered = MethodChannel("com.example/typo")
println(unregistered.invokeMethod("getDeviceId"))
val channel = MethodChannel("com.example/native_bridge")
channel.setMethodCallHandler { method, args ->
when (method) {
"getDeviceId" -> Success("device-abc-123")
"readConfig" ->
if (args["exists"] == true) Success("{theme: dark}")
else Error("IO_ERROR", "config.json not found")
else -> NotImplemented
}
}
println(channel.invokeMethod("getDeviceId"))
println(channel.invokeMethod("readConfig", mapOf("exists" to true)))
println(channel.invokeMethod("readConfig", mapOf("exists" to false)))
println(channel.invokeMethod("openCamera"))
}Expected output:
MissingPluginException: no handler on com.example/typo
Success: device-abc-123
Success: {theme: dark}
PlatformException(IO_ERROR): config.json not found
MissingPluginException: openCamera not implemented
In production
- After a release, users reported a laggy settings screen on low-end Android devices, and the Play Console showed new ANRs.
- The screen called
invokeMethod('getDeviceInfo')insidebuild(), so everysetState(each switch toggle) sent another native call. - The Kotlin handler read several files and queried a system service directly in the
MethodCallHandler, on the main thread, so each call blocked the UI.
- The call moved out of
build()into the screen's state holder, which fetches the device info once and exposes it as state. - The Kotlin handler now does the slow work in a coroutine on
Dispatchers.IOand callsresult.successwhen it finishes. - Code review now checks two things for every channel: no
invokeMethodinbuild(), and no blocking work directly inside a handler.
- Battery usage complaints came in for a fitness app, and Android's battery stats showed the accelerometer active long after users left the workout screen.
- The Dart screen listened to
receiveBroadcastStream()but never stored or cancelled the subscription. - Because the Dart subscription was never cancelled,
onCancelnever ran on Android, so theSensorEventListenerstayed registered. The logs also showedsetState() called after dispose().
- The screen stores the
StreamSubscriptionin a field and callscancel()indispose(), which triggersonCanceland unregisters the listener. - A widget test mocks the event channel with
setMockStreamHandler, opens and closes the screen, and asserts that the mock received a cancel. - The
cancel_subscriptionslint was enabled to flag subscriptions that are never cancelled.
Common mistakes
- Calling invokeMethod inside build(). Every rebuild sends another native call, and calls with side effects run again and again. Fetch once in
initStateor a state holder and render the result. - Doing blocking work in the Android handler. Handlers run on the main thread by default, so file, database, or network work there freezes the UI and can cause an ANR. Use a coroutine with
Dispatchers.IOor a backgroundTaskQueue. - Not replying, or replying twice. Every method call must get exactly one
success,error, ornotImplemented. A missing reply leaves the DartFuturewaiting forever; a second reply throws on the native side. - Forgetting to cancel an EventChannel subscription.
onCancelnever runs, so native listeners stay registered, draining battery and sending events to a screen that no longer exists. Store the subscription and cancel it indispose(). - Hand-writing maps for complex data instead of using Pigeon. Manual
Map<String, dynamic>casting fails at runtime when a key is renamed on one side. Pigeon generates typed classes so both sides break at compile time instead. - Ignoring channel errors on the Dart side. An uncaught
PlatformExceptionsurfaces as an unhandled error and the feature silently fails. Catch it at the wrapper, map error codes to meaningful app errors, and show a fallback.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What happens, step by step, when Dart calls MethodChannel.invokeMethod on Android?”
“How does EventChannel differ from MethodChannel, and when would you use each?”
“When would you choose Pigeon over a raw MethodChannel?”
“How do you debug a MissingPluginException on Android?”
Quiz
What does MethodChannel.invokeMethod<T> return on the Dart side?
On Android, on which thread does a MethodCallHandler run by default?
What is the default codec behind MethodChannel and EventChannel?
What makes the Android StreamHandler's onCancel run for an EventChannel?
0 of 4 answered
Mini task
15-minute exercise: add a MethodChannel to a Flutter app
-
Dart side. In
lib/native_bridge.dart, create aMethodChannel('com.example/native_bridge')and aFuture<String> getDeviceId()that callsinvokeMethod<String>('getDeviceId')and returns the result or'unknown'. -
Android side. In
android/app/src/main/kotlin/.../MainActivity.kt, overrideconfigureFlutterEngine, create aMethodChannelonflutterEngine.dartExecutor.binaryMessengerwith the same name, and callsetMethodCallHandler. Reply togetDeviceIdwithSettings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)and callresult.notImplemented()for anything else. -
Call it from the UI. Add a button whose
onPressedcallsgetDeviceId()and stores the result in asetState-backed field. Show the result below the button. -
Handle errors. Catch
PlatformExceptionandMissingPluginExceptionand show a readable message instead of failing silently. -
Verify. Run
flutter runon an Android device or emulator and tap the button. Then change the method name on the Dart side togetDeviceIdd, rebuild, and confirm theMissingPluginExceptionmessage appears.
Done condition: The button shows the device ID on success and a readable error on failure, with no unhandled exceptions in the logs.