Platform channels

Learn Flutter platform channels for Android: MethodChannel, EventChannel and Pigeon between Dart and Kotlin, with codecs, threading, errors and testing. About 25 minutes.

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.
  • MissingPluginException and PlatformException are 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.

ChannelDirectionTypical use
MethodChannelEither side can call the other; one reply per callOne-shot calls: read a setting, start a native flow
EventChannelNative to Dart stream, started and stopped by the Dart listenerContinuous data: sensor readings, connectivity changes
BasicMessageChannelEither direction, plain messages with a chosen codecSimple message passing without method names
Pigeon (code generator)Generates typed APIs in both directionsStructured 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.

One MethodChannel call, there and back
One MethodChannel call, there and back Dart calls invokeMethod with a method name and arguments. The codec encodes them and the binary messenger delivers the call to the Kotlin MethodCallHandler on the Android main thread. The handler replies once with result.success, or with an error. The reply is decoded and the Dart Future completes with the value, or throws a PlatformException. Must reply exactly once result.error becomes a PlatformException invokeMethod(name, args) ENCODED, MAIN THREAD result.success(value) FUTURE COMPLETES Dart Flutter side Codec + messenger BinaryMessenger Kotlin handler MethodCallHandler
The handler runs on the Android main thread and must reply exactly once; an error reply becomes a PlatformException in Dart.

Notes

  • MethodChannel is for request and reply, EventChannel for native-to-Dart streams, BasicMessageChannel for plain messages, and Pigeon for generated, type-safe APIs.
  • invokeMethod<T> returns Future<T?>. The native side can reply with null, so handle it.
  • In a custom app channel, register handlers in FlutterActivity.configureFlutterEngine(flutterEngine) using flutterEngine.dartExecutor.binaryMessenger. In a plugin, implement FlutterPlugin and register in onAttachedToEngine, using binding.binaryMessenger.
  • Handlers run on the main thread. Move slow work off it (a coroutine with withContext(Dispatchers.IO), or a background TaskQueue), and reply when the work finishes. Every call must get exactly one reply.
  • PlatformException on the Dart side carries the code, message, and details passed to result.error. Use stable error codes so Dart can branch on them.
  • MissingPluginException means 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 marked notImplemented.
  • StandardMessageCodec cannot send arbitrary objects. Convert to maps and lists, extend StandardMessageCodec with writeValue and readValueOfType for custom types, or let Pigeon generate the codec.
  • Cancel the StreamSubscription from receiveBroadcastStream() in dispose(). That is what triggers onCancel on Android, where you unregister sensors and listeners.
  • Do not call invokeMethod from build(). Call it from initState, 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 a Texture widget backed by a native surface. Channels are asynchronous and copy every message.
  • In tests, mock a channel with TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler so 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.
  • readConfig does file I/O on Dispatchers.IO and replies after switching back, so the main thread never blocks and result is called on it. MainScope needs kotlinx-coroutines-android on the classpath.
  • Only IOException is caught, so coroutine cancellation still propagates normally.
  • onCancel unregisters the sensor listener. It only runs if the Dart side cancels its subscription, which is why dispose() must call cancel().
  • 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

Settings screen janks and triggers ANRs
  • 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') inside build(), so every setState (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 fix
  • 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.IO and calls result.success when it finishes.
  • Code review now checks two things for every channel: no invokeMethod in build(), and no blocking work directly inside a handler.
Accelerometer kept running after leaving the workout screen
  • 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, onCancel never ran on Android, so the SensorEventListener stayed registered. The logs also showed setState() called after dispose().
The fix
  • The screen stores the StreamSubscription in a field and calls cancel() in dispose(), which triggers onCancel and 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_subscriptions lint 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 initState or 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.IO or a background TaskQueue.
  • Not replying, or replying twice. Every method call must get exactly one success, error, or notImplemented. A missing reply leaves the Dart Future waiting forever; a second reply throws on the native side.
  • Forgetting to cancel an EventChannel subscription. onCancel never runs, so native listeners stay registered, draining battery and sending events to a screen that no longer exists. Store the subscription and cancel it in dispose().
  • 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 PlatformException surfaces 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

  1. Dart side. In lib/native_bridge.dart, create a MethodChannel('com.example/native_bridge') and a Future<String> getDeviceId() that calls invokeMethod<String>('getDeviceId') and returns the result or 'unknown'.

  2. Android side. In android/app/src/main/kotlin/.../MainActivity.kt, override configureFlutterEngine, create a MethodChannel on flutterEngine.dartExecutor.binaryMessenger with the same name, and call setMethodCallHandler. Reply to getDeviceId with Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) and call result.notImplemented() for anything else.

  3. Call it from the UI. Add a button whose onPressed calls getDeviceId() and stores the result in a setState-backed field. Show the result below the button.

  4. Handle errors. Catch PlatformException and MissingPluginException and show a readable message instead of failing silently.

  5. Verify. Run flutter run on an Android device or emulator and tap the button. Then change the method name on the Dart side to getDeviceIdd, rebuild, and confirm the MissingPluginException message appears.

Done condition: The button shows the device ID on success and a readable error on failure, with no unhandled exceptions in the logs.

Next: Flutter performance and rendering