Dev Pattern Labs logo
Dev Pattern Labs Blog
Android & Flutter 6 min readOct 22, 2026

Flutter Platform Channels: Calling Native Android APIs in Kotlin from Flutter

Master Flutter platform channels in Android Studio. Build MethodChannels and EventChannels to invoke native Kotlin APIs, sensors, and background services.

Dev Pattern Labs Author

Dev Pattern Labs

Peer-reviewed technical tutorial · Production tested

Kotlin code on Android Studio screen communicating with Flutter application
Executive Summary & Key Insight

Master Flutter platform channels in Android Studio. Build MethodChannels and EventChannels to invoke native Kotlin APIs, sensors, and background services. This practical guide covers step-by-step setup, real-world code snippets, security hardening, and common production edge cases.

Introduction

While Flutter's extensive package repository on pub.dev covers common use cases like camera, GPS, and Bluetooth, real-world enterprise applications frequently require access to proprietary native Android APIs.

Whether you are communicating with custom POS thermal printers, integrating specialized biometric SDKs, interacting with proprietary hardware sensors, or managing native Android Foreground Services, Flutter Platform Channels provide the bridge between Dart and native Kotlin code.

Inside Android Studio, writing and debugging platform channels is seamless because you can edit Dart and Kotlin side-by-side with full compiler diagnostics.

In this guide, you will learn how to:

  1. Implement a two-way asynchronous MethodChannel
  2. Stream real-time native data back to Flutter using an EventChannel
  3. Handle type conversion and null safety between Dart and Kotlin
  4. Debug native crashes directly within Android Studio Logcat

Prerequisites

  • Android Studio with the Flutter and Dart plugins enabled
  • Kotlin 1.9+ or 2.0+ configured in your android/build.gradle.kts
  • Android device or emulator running API 26+ (Android 8.0+)

1. Architectural Concept: How Platform Channels Work

Flutter and the native Android host communicate via asynchronous message passing over an encrypted binary messenger:

┌─────────────────────────────────┐               ┌─────────────────────────────────┐
│        FLUTTER (DART)           │               │         ANDROID (KOTLIN)        │
│                                 │               │                                 │
│  MethodChannel.invokeMethod()   │ ────Binary──► │  MethodChannel.MethodCallHandler│
│  "getBatteryLevel"              │   Messenger   │  onMethodCall("getBatteryLevel")│
│                                 │               │                                 │
│  Receive Result Future<int>     │ ◄──Binary──── │  result.success(batteryLevel)   │
└─────────────────────────────────┘               └─────────────────────────────────┘

The key rule: Messages and responses are asynchronous to ensure the Flutter 60/120fps UI thread never blocks while native Android executes background tasks.


2. Implementing an Asynchronous MethodChannel

Let's build a practical native feature: reading exact battery level and hardware charging state directly from Android's BatteryManager.

Step 1: The Flutter Client Code in Dart

Create lib/services/native_battery_service.dart:

import 'package:flutter/services.dart';

class NativeBatteryService {
  // Define a unique channel identifier (reverse domain name convention)
  static const MethodChannel _channel =
      MethodChannel('com.devpatternlabs.app/battery');

  /// Fetches current battery percentage from native Android
  Future<int> getBatteryLevel() async {
    try {
      final int result = await _channel.invokeMethod('getBatteryLevel');
      return result;
    } on PlatformException catch (e) {
      throw Exception('Failed to get native battery level: ${e.message}');
    } on MissingPluginException {
      throw Exception('Platform channel not implemented on this host platform.');
    }
  }

  /// Checks if device is plugged into AC or USB power
  Future<bool> isCharging() async {
    try {
      final bool charging = await _channel.invokeMethod('isCharging');
      return charging;
    } on PlatformException catch (e) {
      throw Exception('Charging status error: ${e.message}');
    }
  }
}

3. The Native Kotlin Implementation in Android Studio

Open the android/ subfolder directly in Android Studio as a separate native project, or navigate to android/app/src/main/kotlin/.../MainActivity.kt.

MainActivity.kt with Kotlin MethodChannel

package com.devpatternlabs.mymobileapp

import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val BATTERY_CHANNEL = "com.devpatternlabs.app/battery"

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

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, BATTERY_CHANNEL)
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "getBatteryLevel" -> {
                        val batteryLevel = getBatteryLevel()
                        if (batteryLevel != -1) {
                            result.success(batteryLevel)
                        } else {
                            result.error("UNAVAILABLE", "Battery level not available.", null)
                        }
                    }
                    "isCharging" -> {
                        val isCharging = checkIsCharging()
                        result.success(isCharging)
                    }
                    else -> {
                        result.notImplemented()
                    }
                }
            }
    }

    private fun getBatteryLevel(): Int {
        return if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
            batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
        } else {
            val intent = ContextWrapper(applicationContext).registerReceiver(
                null,
                IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            )
            val level = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
            val scale = intent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
            if (level >= 0 && scale > 0) (level * 100) / scale else -1
        }
    }

    private fun checkIsCharging(): Boolean {
        val intent = ContextWrapper(applicationContext).registerReceiver(
            null,
            IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        )
        val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
        return status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL
    }
}

4. Real-time Native Streaming with EventChannel

When native Android needs to push data continuously (such as live accelerometer data, charging plug/unplug events, or beacon telemetry), use an EventChannel.

Step 1: Dart Stream Subscription

class BatteryEventStream {
  static const EventChannel _eventChannel =
      EventChannel('com.devpatternlabs.app/battery_stream');

  Stream<String> get onBatteryStatusChanged {
    return _eventChannel
        .receiveBroadcastStream()
        .map((dynamic event) => event.toString());
  }
}

Step 2: Kotlin StreamHandler in Android Studio

import io.flutter.plugin.common.EventChannel

class BatteryStreamHandler(private val context: Context) : EventChannel.StreamHandler {
    private var receiver: BroadcastReceiver? = null

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
                val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
                events?.success(if (isCharging) "CHARGING" else "DISCHARGING")
            }
        }
        context.registerReceiver(receiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
    }

    override fun onCancel(arguments: Any?) {
        context.unregisterReceiver(receiver)
        receiver = null
    }
}

Register inside configureFlutterEngine:

EventChannel(flutterEngine.dartExecutor.binaryMessenger, "com.devpatternlabs.app/battery_stream")
    .setStreamHandler(BatteryStreamHandler(context))

5. Dart to Kotlin Type Mapping Reference

When passing complex parameters, the StandardMessageCodec automatically serializes types:

Dart TypeKotlin / Android Type
nullnull
booljava.lang.Boolean (Boolean)
intjava.lang.Integer (if 32-bit) or java.lang.Long
doublejava.lang.Double (Double)
Stringjava.lang.String (String)
Uint8ListByteArray (byte[])
Listjava.util.ArrayList<*>
Mapjava.util.HashMap<*, *>

6. Debugging Native Channels in Android Studio

When a channel fails, follow this debugging sequence:

  1. MissingPluginException: Verify that the channel string (com.devpatternlabs.app/...) matches character-for-character in both MethodChannel(name) in Dart and MethodChannel(dartExecutor, name) in Kotlin.
  2. TypeCastException in Kotlin: Always cast arguments safely:
    val param = call.argument<String>("myKey") ?: "default_value"
    
  3. Logcat 2.0: Search with tag:flutter or your custom Kotlin tag to inspect native exceptions without crashing the Dart engine.

Conclusion & Architecture Recommendations

Platform channels allow you to harness the full power of native Android without sacrificing the cross-platform productivity of Flutter:

  • Use MethodChannel for request/response operations.
  • Use EventChannel for continuous sensor, network, or hardware event streams.
  • Always handle PlatformException on the Dart side to maintain app stability.
  • Open the android folder in Android Studio whenever editing Kotlin to ensure full compiler linting.

Companion Mobile Architecture Tutorials

Tags:#Flutter#Android Studio#Kotlin#Platform Channels#MethodChannel#native Android
Dev Pattern Labs Engineering Team

Written by Dev Pattern LabsCore Engineering

Dev Pattern Labs is an engineering lab and digital consultancy specializing in custom Next.js web applications, WooCommerce REST API integrations, and workflow automation for growing businesses.

Recommended Companion Articles