Sub topic 7
Talking to native code with platform channels
A Flutter module embedded in a native app rarely works alone. It needs the signed-in user, a feature flag, or a way to tell the host that checkout finished. Platform channels carry these messages between the Dart code and the native host. This chapter explains the working model, shows both sides of a channel, and covers the errors that most often break it.
This chapter assumes you can run a Flutter module inside an Android or iOS host, as covered in the integration chapters. It also assumes you know how to cache a FlutterEngine. You should be comfortable with Dart Futures and with Kotlin or Swift closures.
The working model
A platform channel is a named, asynchronous message pipe between Dart and the host. Messages travel through the FlutterEngine's binary messenger. Each channel has three parts:
- A name, a string such as
com.example.host/session. Both sides must use the exact same string. - A codec, which converts values to bytes and back. The default for
MethodChannelis the standard method codec. - A handler, which is code registered on one side to answer calls from the other side.
Because every channel is tied to the engine's messenger, a channel exists per engine. If your app has two engines, you register the handler on each one.
Channel types
| Channel type | Direction and shape | Typical use |
|---|---|---|
| `MethodChannel` | Request and response, either direction | "Get the user name", "close the screen" |
| `EventChannel` | Native sends a stream of events to Dart | Location updates, connectivity changes |
| `BasicMessageChannel` | Plain messages with a custom codec | Simple string or binary exchange |
This chapter concentrates on MethodChannel, which covers most add-to-app needs.
Supported types
The standard codec supports a fixed set of types. Anything else must be converted first.
| Dart | Kotlin / Java | Swift / Objective-C |
|---|---|---|
| `null` | `null` | `nil` |
| `bool` | `Boolean` | `NSNumber(value: Bool)` |
| `int` | `Int` or `Long` | `NSNumber(value: Int)` |
| `double` | `Double` | `NSNumber(value: Double)` |
| `String` | `String` | `String` |
| `List` | `List` | `Array` |
| `Map` | `HashMap` | `Dictionary` |
| `Uint8List` | `byte[]` | `FlutterStandardTypedData` |
A Dart int arrives as a Kotlin Int when the value fits in 32 bits and as a Long otherwise. Code that casts to one type can fail on large values.
The Dart side
The module from the earlier chapters asks the host for a user name. The relevant part is small:
import 'package:flutter/services.dart';
const _channel = MethodChannel('com.example.host/session');
Future<String> loadUserName() async {
final name = await _channel.invokeMethod<String>('getUserName');
return name ?? 'guest';
}invokeMethod<String> returns a Future<String?>. The result is null when the host returns null. The call can also throw, so a production version should catch two exceptions:
import 'package:flutter/services.dart';
const _channel = MethodChannel('com.example.host/session');
Future<String> loadUserNameSafely() async {
try {
final name = await _channel.invokeMethod<String>('getUserName');
return name ?? 'guest';
} on MissingPluginException {
// No handler registered on this engine, or the module runs standalone.
return 'guest';
} on PlatformException catch (e) {
// The host called result.error(...).
return 'error: ${e.code}';
}
}MissingPluginException is the most common failure in add-to-app. It is thrown when the host has not registered a handler for the channel or method. It also appears when you run the module alone with flutter run, because no host exists. Catching it lets the module keep working in that mode.
The Android side
On Android you register the handler on the engine's dartExecutor.binaryMessenger. Using the cached engine from the earlier chapter:
import android.app.Application
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
val engine = FlutterEngine(this)
// Register handlers BEFORE running Dart, so early calls are answered.
MethodChannel(engine.dartExecutor.binaryMessenger, "com.example.host/session")
.setMethodCallHandler { call, result ->
when (call.method) {
"getUserName" -> result.success("Ada")
else -> result.notImplemented()
}
}
engine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
FlutterEngineCache.getInstance().put("main_engine", engine)
}
}Registering in Application.onCreate has a practical advantage over registering in an Activity. The handler exists as soon as the engine starts, so a Dart initState that calls the host immediately does not hit a MissingPluginException. It also means the handler is registered once, not on every screen launch.
A handler that needs an Activity or other short-lived object can leak it if the object is stored on a long-lived engine. Hold such objects in a weak reference, or clear the handler when the screen goes away:
channel.setMethodCallHandler(null)Answering from the host
Every handler call must end with exactly one of three replies:
result.success(value)returns a value, ornull.result.error(code, message, details)makes the DartFuturethrow aPlatformException.result.notImplemented()makes the DartFuturethrowMissingPluginException.
If the handler never replies, the Dart Future never completes. That leaves the screen waiting forever. Replying twice raises an error in the host.
The iOS side
On iOS you create the channel from the engine's binaryMessenger. This sketch extends the FlutterDependencies class from the iOS integration chapter:
import Flutter
import FlutterPluginRegistrant
final class FlutterDependencies {
let engine = FlutterEngine(name: "main_engine")
init() {
let channel = FlutterMethodChannel(
name: "com.example.host/session",
binaryMessenger: engine.binaryMessenger
)
channel.setMethodCallHandler { call, result in
switch call.method {
case "getUserName":
result("Ada")
default:
result(FlutterMethodNotImplemented)
}
}
engine.run()
GeneratedPluginRegistrant.register(with: engine)
}
}The three replies map as follows: calling result(value) succeeds, result(FlutterError(code:message:details:)) fails, and result(FlutterMethodNotImplemented) reports a missing method. Handlers run on the main thread by default on both platforms. Do slow work on a background thread and call result when it finishes. The reply itself may be sent from any thread on Android, but follow the platform guidance and reply on the main thread to stay safe.
Calls in the other direction
A channel works both ways. The host can call Dart, which is useful for pushing state changes such as a logout:
val channel = MethodChannel(engine.dartExecutor.binaryMessenger, "com.example.host/session")
channel.invokeMethod("userLoggedOut", null)Dart then registers a handler:
import 'package:flutter/services.dart';
const _channel = MethodChannel('com.example.host/session');
void listenForHostEvents(void Function() onLogout) {
_channel.setMethodCallHandler((call) async {
switch (call.method) {
case 'userLoggedOut':
onLogout();
return null;
default:
throw MissingPluginException('Unknown method ${call.method}');
}
});
}A call from the host is lost if Dart has not yet registered its handler. With a pre-warmed engine, Dart runs main shortly after startup, but a screen that registers the handler later can miss early events. Register Dart handlers in main before runApp, and call WidgetsFlutterBinding.ensureInitialized() first when you do.
Telling the host the Flutter screen is done
A common add-to-app need is closing the Flutter screen from Dart. Flutter has no direct way to dismiss a host Activity or FlutterViewController, so you add a method for it. Dart calls _channel.invokeMethod('closeScreen'). The Android handler calls activity.finish(). The iOS handler calls dismiss(animated: true). The host must hold a reference to the current screen to do this.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `MissingPluginException` on first call | Handler registered after Dart ran, on a different engine, or name mismatch | Register before `executeDartEntrypoint` or `engine.run()`, and compare names character by character |
| `MissingPluginException` only with `flutter run` | No host exists in standalone mode | Catch the exception and supply a default |
| `Future` never completes | Handler returned without calling `result` on some branch | Make every `when` or `switch` branch reply |
| `ClassCastException` or `Int` vs `Long` crash | Value outside the supported types or wrong numeric width | Use `Number` and call `toLong()`, or send a `String` |
| Host call to Dart is dropped | Dart handler not yet registered | Register in `main` before `runApp` |
| Handler works for one screen only | Second engine created without its own handler | Register on every engine, such as those from an engine group |
| Memory not released | Handler holds an `Activity` or view controller | Use weak references, clear the handler on teardown |
Testing a channel without a host
You can test Dart code that uses a channel by mocking it. This keeps tests free of native code:
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('loads the user name from the host', () async {
const channel = MethodChannel('com.example.host/session');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'getUserName') return 'Ada';
return null;
});
final name = await channel.invokeMethod<String>('getUserName');
expect(name, 'Ada');
});
}The same mock can return a PlatformException to confirm that your error branch behaves as intended.
Summary of the design choices
- Register handlers before the engine runs Dart, ideally where the engine is created.
- Use one channel name per area of responsibility, not one per method.
- Handle both
MissingPluginExceptionandPlatformExceptionin Dart. - Reply exactly once from every handler branch.
- Move to Pigeon when the interface grows past a handful of methods.
Exercise
Your Flutter screen calls invokeMethod('getUserName') in initState. The first launch throws MissingPluginException, but later launches work. The Android host registers the handler inside the Activity that starts FlutterActivity, and the engine is created in Application.onCreate. What is the likely cause, and how do you fix it?
Show answer
The engine starts running Dart in Application.onCreate, so Dart can call the channel before the Activity registers the handler. The first call then finds no handler. Move the setMethodCallHandler registration to Application.onCreate, before executeDartEntrypoint, so the handler exists from the moment Dart starts.
Exercise
A Kotlin handler for getCount has this branch: "getCount" -> { val n = loadCount(); }. It never calls result. What does Dart observe, and what is the correction?
Show answer
The Dart Future from invokeMethod never completes, so the screen waits forever and no exception is thrown. Call result.success(n) in that branch. Every branch must reply once with success, error, or notImplemented.
Exercise
Why does the Dart code in this chapter catch MissingPluginException even when the host does register a handler?
Show answer
The module can also run standalone with flutter run, where no host exists. In that mode every channel call throws MissingPluginException. Catching it lets the module fall back to a default value, such as guest, and stay usable during development.