Flutter Platform Channels: Calling Native Code Cleanly

When Flutter doesn't have a plugin for what you need, platform channels let you call native iOS or Android code. Here's a clean pattern that scales.

Richard GamoraRichard GamoraFullstack developer·4 min read
FlutterPlatform ChannelsiOSAndroid

Most things you need in Flutter exist as a plugin. Sometimes nothing fits — an unusual hardware feature, a private SDK, a specific iOS or Android API. Platform channels let you bridge to native code, and the API is straightforward once you have a clean structure.

Two layers, one channel

On the Dart side, you create a MethodChannel with a name. You call invokeMethod() with a method name and arguments. On the native side, you register a handler on the same channel name and respond to method calls.

dart// Dart
class Battery {
  static const _channel = MethodChannel('app.com/battery');

  static Future<int> getLevel() async {
    return await _channel.invokeMethod<int>('getLevel') ?? -1;
  }
}

On the iOS side

swiftlet channel = FlutterMethodChannel(
  name: "app.com/battery",
  binaryMessenger: controller.binaryMessenger
)
channel.setMethodCallHandler { call, result in
  if call.method == "getLevel" {
    result(Int(UIDevice.current.batteryLevel * 100))
  } else {
    result(FlutterMethodNotImplemented)
  }
}

Keep the boundary thin

Pass primitive types and small maps across the channel. Anything bigger should be referenced (an ID) and fetched separately. Serializing large objects across the boundary is slow and brittle.

Make a Dart class around it

Wrap each channel in a typed Dart class with named methods. Callers should never see invokeMethod or the raw method names. The class is also where you handle exceptions — convert FlutterError into a typed result your app can act on.

About the author

Richard Gamora

Richard Gamora

Fullstack developer based in the Philippines, working mostly with Laravel and Vue.js, with eight years of production experience across web and mobile.

me@richardgamora.comUpwork ↗

More on Flutter