11. Platform Channels & Native Interop

MethodChannels & EventChannels Architecture

Master native mobile interoperability: BinaryMessenger mechanics, StandardMessageCodec type mapping, request-response MethodChannels, and real-time native sensor streams with EventChannels across Kotlin and Swift.

1. Platform Channels Architecture

When Flutter needs to access native hardware APIs (e.g. Battery Manager, Bluetooth, NFC, Camera, HealthKit), it communicates across the Platform Channel pipeline:

MethodChannel.invokeMethod('getBatteryLevel') Serializes method & args into binary ByteData buffer Dispatches binary message across native shell boundary Returns native result (e.g., 85%) Serializes return value into binary ByteData Resolves Future<int> with 85 Kotlin / Swift executes OS API(e.g., BatteryManager.getIntProperty) Flutter Dart Layer StandardMessageCodec BinaryMessenger (C++ Engine) Native Host (Kotlin / Swift)

2. Standard Type Serialization Table

The StandardMessageCodec automatically translates standard data types across language boundaries without manual JSON encoding:

Dart TypeAndroid (Kotlin / Java)iOS (Swift / Objective-C)
nullnullnil (NSNull)
booljava.lang.Boolean / BooleanNSNumber numberWithBool: / Bool
intjava.lang.Integer (32-bit) / Long (64-bit)NSNumber numberWithInt: / Int
doublejava.lang.Double / DoubleNSNumber numberWithDouble: / Double
Stringjava.lang.String / StringNSString / String
Uint8Listbyte[] / ByteArrayFlutterStandardTypedData / Data
List<dynamic>java.util.ArrayList / ListNSArray / Array
Map<dynamic, dynamic>java.util.HashMap / MapNSDictionary / Dictionary

3. End-to-End MethodChannel Implementation

1. Dart Client Implementation

import 'package:flutter/services.dart';

class DeviceBatteryService {
  static const MethodChannel _channel = MethodChannel('com.example.app/battery');

  static Future<int> fetchBatteryLevel() async {
    try {
      final int? batteryLevel = await _channel.invokeMethod<int>('getBatteryLevel');
      return batteryLevel ?? -1;
    } on PlatformException catch (e) {
      print("⚠️ Platform error: ${e.code} - ${e.message}");
      return -1;
    }
  }
}

2. Android Kotlin Implementation (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() {
    private val CHANNEL = "com.example.app/battery"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "getBatteryLevel") {
                val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
                val level = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)

                if (level != -1) {
                    result.success(level) // Return integer to Dart
                } else {
                    result.error("UNAVAILABLE", "Battery level not available.", null)
                }
            } else {
                result.notImplemented()
            }
        }
    }
}

3. iOS Swift Implementation (AppDelegate.swift)

import Flutter
import UIKit

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let batteryChannel = FlutterMethodChannel(name: "com.example.app/battery",
                                              binaryMessenger: controller.binaryMessenger)

    batteryChannel.setMethodCallHandler({
      (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
      guard call.method == "getBatteryLevel" else {
        result(FlutterMethodNotImplemented)
        return
      }
      
      UIDevice.current.isBatteryMonitoringEnabled = true
      let level = Int(UIDevice.current.batteryLevel * 100)
      if level >= 0 {
        result(level) // Return integer to Dart
      } else {
        result(FlutterError(code: "UNAVAILABLE", message: "Battery level unavailable", details: nil))
      }
    })

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

4. Continuous Streaming: EventChannel

When the native OS pushes continuous sensor readings or location updates:

// Dart Side: Listen to native sensor stream
class AccelerometerService {
  static const EventChannel _eventChannel = EventChannel('com.example.app/accelerometer');

  static Stream<List<double>> get sensorStream {
    return _eventChannel.receiveBroadcastStream().map((dynamic event) {
      final List<dynamic> raw = event as List<dynamic>;
      return raw.map((e) => (e as num).toDouble()).toList();
    });
  }
}

❓ Knowledge Check

Knowledge Check

What is the role of BinaryMessenger in Flutter's platform channel architecture?

Knowledge Check

What happens if a MethodChannel on the native side calls result.notImplemented()?

On this page