DEV Community

Cover image for Flutter Method Channels: Native Code
Muhammad Uzair
Muhammad Uzair

Posted on Originally published at uzairxdev.online

Flutter Method Channels: Native Code

Flutter ships with a huge widget library and a package for almost everything, yet every production app eventually needs something Flutter does not expose: a system setting, a vendor SDK, or a hardware feature that only exists in native code. When that day comes, the answer is not to rewrite the app natively. It is a method channel, the small, well-defined bridge Flutter provides between Dart and the platform code underneath it.

This guide builds a complete method channel from scratch. The example reads the battery level, first from Dart, then with a Kotlin handler on Android and a Swift handler on iOS, and finishes with arguments, error handling, and tests.

What is a Flutter method channel?

A Flutter method channel is a named, asynchronous bridge that lets Dart code invoke a method implemented in Kotlin or Swift on the host platform and receive a result back. The two sides agree on two strings: the channel name, such as com.example.app/battery, and the method name, such as getBatteryLevel. Dart sends a method call with optional arguments, the native side runs the code, and the answer comes back as a value, an error, or a not-implemented reply.

Messages travel through the platform binary messenger, encoded with the standard message codec, so both sides only ever exchange the types the codec understands: null, booleans, numbers, strings, byte arrays, lists, and maps. The call is always asynchronous on the Dart side, so the UI thread never blocks while native code runs. A channel is not a plugin by itself. It is the mechanism plugins are built on, and writing one directly is the fastest way to reach a native API when no package exists.

When should you use a method channel?

Use a method channel when Flutter or its package ecosystem cannot reach the native capability your app needs: a system setting Flutter does not expose, a vendor SDK that ships only as a native library, or a hardware feature with no Dart package. Reach for a maintained package first when one exists, because it carries the native code, the tests, and the platform edge cases for you. Never use a channel for logic that can live in pure Dart, because every crossing adds a failure mode that Dart-only code does not have.

Situation What to do
System setting Flutter does not expose, such as the ringer mode or the exact alarm schedule Write a method channel
Vendor SDK with no maintained Dart package Write a thin method channel wrapper around the SDK
Common feature such as the camera, maps, or payments Use a maintained package from pub.dev
Pure Dart logic, such as formatting, validation, or state No channel at all

A real example from this site is Smart Silent, which switches the Android ringer mode automatically by schedule or location. That needs deep OS-level controls to manage media, calls, and notification volumes, which Flutter does not expose, so a platform channel is the only way to build it. The same pattern shows up in the guides on controlling the Android ringer mode and exact alarm scheduling on Android.

How does a method channel work?

A method channel has three parts, and all three must agree. The Dart side creates a MethodChannel with a name and calls invokeMethod with a method name and optional arguments. The native side registers a handler for the same channel name in the app's MainActivity on Android or AppDelegate on iOS. The binary messenger carries the encoded message between them and delivers the result back to the awaiting Dart Future.

How do you call native code from Dart?

The Dart side of a method channel is a small class that owns one MethodChannel and exposes typed methods around it. The battery example below calls a native method named getBatteryLevel and returns the level as an integer, or -1 when the value cannot be read. Every call is awaited, and every failure is caught, because a native call can fail for reasons Dart cannot predict.

import 'package:flutter/services.dart';

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

  Future<int> getBatteryLevel() async {
    try {
      final int? level = await _channel.invokeMethod<int>('getBatteryLevel');
      return level ?? -1;
    } on PlatformException catch (e) {
      debugPrint('Battery level failed: ' + e.code);
      return -1;
    } on MissingPluginException {
      debugPrint('No native handler registered for the battery channel.');
      return -1;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

How do you handle the call on Android with Kotlin?

On Android, the handler lives in MainActivity and is registered in configureFlutterEngine, which runs once when the Flutter engine attaches to the activity. The handler receives the method name and a result object, and it must answer every call with exactly one of three replies: result.success with a value, result.error with a code and message, or result.notImplemented for a method name it does not know. The handler runs on the platform thread, so slow work must move to a background thread or coroutine, and the result must be delivered after that work finishes.

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 channelName = "com.example.app/battery"

  override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
      .setMethodCallHandler { call, result ->
        if (call.method == "getBatteryLevel") {
          val level = getBatteryLevel()
          if (level != -1) {
            result.success(level)
          } else {
            result.error("UNAVAILABLE", "Battery level not available.", null)
          }
        } else {
          result.notImplemented()
        }
      }
  }

  private fun getBatteryLevel(): Int {
    val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
    return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
  }
}
Enter fullscreen mode Exit fullscreen mode

How do you handle the call on iOS with Swift?

On iOS, the handler lives in AppDelegate and is registered in application:didFinishLaunchingWithOptions:, using the binary messenger from the root FlutterViewController. The shape is the same as Android: match the method name, run the native code, and answer with a value, a FlutterError, or FlutterMethodNotImplemented. iOS reports the battery level as a float between 0.0 and 1.0, so the handler converts it to the same integer percentage the Android side returns, keeping the Dart code platform-agnostic.

import Flutter
import UIKit

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    let controller = window?.rootViewController as! FlutterViewController
    let channel = FlutterMethodChannel(
      name: "com.example.app/battery",
      binaryMessenger: controller.binaryMessenger)
    channel.setMethodCallHandler { (call, result) in
      if call.method == "getBatteryLevel" {
        UIDevice.current.isBatteryMonitoringEnabled = true
        let level = UIDevice.current.batteryLevel
        if level < 0 {
          result(FlutterError(code: "UNAVAILABLE", message: "Battery level not available.", details: nil))
        } else {
          result(Int(level * 100))
        }
      } else {
        result(FlutterMethodNotImplemented)
      }
    }
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
Enter fullscreen mode Exit fullscreen mode

How do you pass arguments and return results?

Arguments travel as a single value, usually a Map, and the native side reads each key with a typed accessor. The Dart call below passes a map with one entry, and the Kotlin handler reads it with call.argument, falling back to a default when the key is missing. Returning a result works the same way in reverse: a Map or a List of codec-supported values crosses the bridge intact, so a native method can return a small object such as a status plus a value without any extra serialization.

await _channel.invokeMethod<void>('setRingerMode', <String, dynamic>{
  'mode': 'silent',
});
Enter fullscreen mode Exit fullscreen mode
"setRingerMode" -> {
  val mode = call.argument<String>("mode") ?: "normal"
  // Switch the ringer mode here, then confirm the call.
  result.success(null)
}
Enter fullscreen mode Exit fullscreen mode

How do you handle errors the right way?

A method channel has exactly three failure modes, and each one needs a different response in Dart. A PlatformException means the native side answered with result.error, and its code, message, and details fields carry whatever the native code reported. A MissingPluginException means no handler is registered for the channel or the method name, which is almost always a naming mismatch or a handler that was never registered on that platform. Any other exception, such as a codec failure from sending an unsupported type, is a programming error and should surface during development rather than being swallowed.

Failure Cause Dart response
PlatformException Native side called result.error Show a fallback value or a user-facing message
MissingPluginException Wrong channel name, or no handler on this platform Log it, return a fallback, and fix the name
Codec error Unsupported type crossed the bridge Fix the type during development, never in production

How do you test a method channel?

Method channels are easy to test because the test framework can intercept calls before they reach native code. setMockMethodCallHandler registers a fake handler on the test binary messenger that answers with canned values, so the Dart service can be tested without a device or an emulator. Initialise the test binding first, install the mock in setUp, and clear it in tearDown.

import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  const channel = MethodChannel('com.example.app/battery');

  setUp(() {
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
        .setMockMethodCallHandler(channel, (MethodCall call) async {
      if (call.method == 'getBatteryLevel') {
        return 82;
      }
      return null;
    });
  });

  tearDown(() {
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
        .setMockMethodCallHandler(channel, null);
  });

  test('returns the mocked battery level', () async {
    final level = await channel.invokeMethod<int>('getBatteryLevel');
    expect(level, 82);
  });
}
Enter fullscreen mode Exit fullscreen mode

Test the failure paths too: a mock that throws a PlatformException verifies the service returns its fallback. The native handlers themselves cannot be covered by a Dart test, so keep them thin.

What are the common mistakes to avoid?

Most method channel bugs come from the same short list. Different channel names on the Dart and native sides is the most common one, so define the name once per side and copy it exactly. Forgetting result.notImplemented() for unknown methods, or forgetting to answer a call at all, leaves the Dart Future hanging. Blocking the platform thread with network or disk work freezes the app, because the handler runs on the main thread on both platforms. Sending an unsupported type, such as a custom object or a DateTime, fails at the codec before the handler ever runs. Calling a channel before the engine is ready, or after the owning widget is disposed, throws in ways that look unrelated to the channel. And a handler that exists only on Android throws MissingPluginException on iOS, so implement both sides or handle the missing platform explicitly in Dart.

Method channels vs event channels: which one do you need?

A method channel is request-response: Dart asks, native answers, and the conversation ends. That fits one-off reads such as the battery level, and commands such as switching the ringer mode. When the native side needs to push data repeatedly, such as sensor readings, location updates, or download progress, use an EventChannel instead. An event channel opens a stream that the native side feeds over time and Dart listens to like any other Dart stream, so the app receives updates without polling. If you are reaching for a method channel inside a timer to poll a changing value, that is the sign you actually need an event channel.

Method channels are the escape hatch that keeps Flutter apps honest: stay in Dart for everything Flutter does well, and drop to native code only for the few things that genuinely need it. Keep the bridge thin, name both sides identically, answer every call, and test the Dart side with a mock. For a full example of this pattern in a shipped app, see the Smart Silent case study, and the geofencing guide for a battery-friendly take on location-based native work.

Get in touch and let's talk about your project.


Originally published at uzairxdev.online

Top comments (0)