Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 73 ยท Platform integration

Platform Channels and Plugins

Call native Android, iOS and desktop code from Flutter with MethodChannel and EventChannel, generate type-safe APIs with Pigeon, use FFI and write a plugin.

Flutter draws its own pixels, but your app still lives on a real phone with a battery, sensors, a file system and vendor SDKs. Dart cannot call those directly. The bridge is platform channels: named pipes that carry messages between Dart and the host code (Kotlin or Java on Android, Swift or Objective-C on iOS, Swift on macOS, C++ on Windows and Linux).

You will rarely write a channel yourself, because most features already have a plugin. But every plugin is built on channels (or FFI), and knowing how they work lets you debug them, wrap an SDK your company needs, and publish your own package.

Real vs stand-in. The Dart, Kotlin and Swift code below is real and read-only: the site has no Flutter engine or phone. The live examples are JavaScript stand-ins of the message flow (method name plus arguments in, result or error out, and a stream of events) so you can see the contract and the failure modes.

Three ways to reach native

MethodChannel Ask once, get one answer.
EventChannel A stream of events from native.
FFI Call C code directly, no messages.
1 / 2

How a MethodChannel works

A channel has a name, a string that both sides must spell identically, usually reversed-domain style. Dart calls invokeMethod('name', arguments) and gets a Future. The host registers a handler that matches on the method name and replies.

sequenceDiagram
    participant D as Dart
    participant E as Engine
    participant H as Host (Kotlin or Swift)
    D->>E: invokeMethod("getBattery")
    E->>H: message on channel
    H-->>E: result 87 or error
    E-->>D: Future completes

Messages are encoded in a binary format (the standard codec), asynchronously, so the UI thread is not blocked by waiting.

The Dart side

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

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

  Future<int?> level() async {
    try {
      return await _channel.invokeMethod<int>('getBatteryLevel');
    } on PlatformException catch (e) {
      throw StateError('Battery failed: ${e.code} ${e.message}');
    } on MissingPluginException {
      return null;   // no handler on this platform (for example web)
    }
  }
}

The Android side (Kotlin)

Kotlin
class MainActivity : FlutterActivity() {
  override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.example.app/battery")
      .setMethodCallHandler { call, result ->
        when (call.method) {
          "getBatteryLevel" -> {
            val manager = getSystemService(BATTERY_SERVICE) as BatteryManager
            val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
            if (level >= 0) result.success(level) else result.error("UNAVAILABLE", "No battery info", null)
          }
          else -> result.notImplemented()
        }
      }
  }
}

The iOS handler is the same shape in Swift (FlutterMethodChannel(name:binaryMessenger:) and setMethodCallHandler). Every handler ends in exactly one of: success(value), error(code, message, details), or notImplemented().

Which types can cross

The standard codec supports null, bool, int, double, String, Uint8List, Int32List, Int64List, Float64List, List and Map (with supported types inside). Your own classes cannot cross: convert them to a map or a list first. Small numbers arrive as int (Dart) and Int/Long (Kotlin) depending on size, a classic source of cast bugs.

Stand-in: a channel and its failure modes

JS A fake MethodChannel with success, error and missing handler

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three different failures, three different exceptions: handle PlatformException for errors the host reports, and MissingPluginException for "nobody listens", which is what happens on a platform where you did not write the native half.

EventChannel: a stream from native

A MethodChannel answers one question. For continuous data such as sensor readings, connectivity changes or location updates, use an EventChannel. Dart listens to a Stream; the host sends events through an event sink until Dart cancels.

DART
const EventChannel _events = EventChannel('com.example.app/compass');

Stream<double> get heading =>
    _events.receiveBroadcastStream().map((dynamic e) => (e as num).toDouble());

// in a widget: StreamBuilder<double>(stream: service.heading, builder: ...)

On the host, a StreamHandler has onListen(arguments, sink), where you start the sensor and call sink.success(value), and onCancel, where you stop it. Forgetting onCancel is a classic battery drain. For using such a stream in widgets, see FutureBuilder and StreamBuilder.

JS A fake EventChannel with listen and cancel

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Pigeon: typed channels

Hand-written channels use strings for names and untyped maps for data, so typos fail at runtime. Pigeon is a code generator that reads a Dart description of your API and generates matching Dart, Kotlin, Swift (and others) code with real types:

DART
// pigeons/messages.dart
class Reading {
  Reading({required this.level, required this.charging});
  int level;
  bool charging;
}

@HostApi()
abstract class BatteryApi {
  Reading read();
  @async
  void setLowPowerMode(bool enabled);
}

After dart run pigeon --input pigeons/messages.dart, Dart calls BatteryApi().read() and gets a Reading; native code implements a generated interface. Pigeon is what the official plugins use. Prefer it whenever an API has more than a couple of methods.

FFI: calling C directly

dart:ffi loads a native library and calls C functions with no message passing, which is useful for existing C/C++/Rust libraries and for performance-critical code. Newer tooling (package:ffigen, native assets/build hooks) generates the bindings and builds the C code with your app.

DART
import 'dart:ffi';

typedef _AddC = Int32 Function(Int32, Int32);
typedef _AddDart = int Function(int, int);

final DynamicLibrary lib = DynamicLibrary.open('libmath.so');
final _AddDart add = lib.lookupFunction<_AddC, _AddDart>('add');
// add(2, 3) == 5

FFI does not exist on the web. It needs care with memory: anything you allocate with calloc, you free.

Writing and publishing a plugin

A plugin package bundles Dart code with native code for one or more platforms; a package is Dart only. Create one with flutter create --template=plugin --platforms=android,ios my_battery. The result has the Dart API in lib/, native code in android/, ios/, and an example/ app for testing. In pubspec.yaml, the flutter: plugin: platforms: section names the class registered for each platform.

Federated plugins

Large plugins are split into several packages so each platform can be maintained separately:

  • the app-facing package (my_battery), the one users depend on;
  • the platform interface (my_battery_platform_interface), an abstract class with a default implementation;
  • one implementation per platform (my_battery_android, my_battery_ios, my_battery_web).

Anyone can add a platform by publishing another implementation, without touching the original. Publish with flutter pub publish after --dry-run passes. Keep the changelog, license, an example and a score-friendly README: pub.dev ranks packages on them.

Common mistakes

  • Mismatched channel names between Dart and native (they are plain strings).
  • Blocking the platform thread in a handler; do slow work on a background thread and call result once on the main thread.
  • Calling result twice or never, which hangs the Dart Future or crashes.
  • Not handling MissingPluginException where the platform has no implementation (for example in tests or on the web).
  • Sending custom objects; convert to maps or use Pigeon.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which channel type fits a continuous stream of compass headings?

    EventChannel exposes a Dart Stream; the host sends events until Dart cancels.
  2. 2. What does MissingPluginException mean?

    It is thrown when nothing answers, for example on a platform without a native implementation.
  3. 3. What is Pigeon for?

    You describe the API once in Dart, and Pigeon generates both sides so names and types cannot drift.
  4. 4. Which of these can NOT be sent over the standard codec as-is?

    Custom classes must be turned into maps or lists (or use Pigeon, which generates the conversion).
  5. 5. In a federated plugin, what does the platform interface package contain?

    It defines the contract; app-facing and per-platform packages depend on it.

Summary

  • Platform channels pass asynchronous, encoded messages between Dart and native code; a name connects both sides.
  • MethodChannel is request/response, EventChannel is a stream; each reply is success, error or notImplemented.
  • Handle PlatformException and MissingPluginException; stop native work in onCancel.
  • Pigeon removes stringly typed code; FFI calls C directly without messages.
  • Plugins package Dart plus native code; federated plugins split one API into per-platform packages.

Next: Camera, Location, Permissions and Notifications