Lesson 6 of 9 · 29m
Platform Channels, FFI, and Native Integration Without Leaks
Design method-channel contracts, handle permissions and lifecycle realities, and decide when FFI or a federated plugin is the right boundary.
Cross-platform development works until the platform matters. Then the microphone permission flow differs on iOS, Android needs a foreground service, Windows has no equivalent API, and web cannot access the file system the same way. The wrong response is a pile of if (Platform.isAndroid) inside widgets. The right response is a narrow, testable native boundary.
Method channels are RPC contracts
A MethodChannel sends named messages between Dart and host code. Treat it like an API, because it is one:
class SecureStorageBridge {
static const _channel = MethodChannel('app.sudosec/secure_storage');
Future<String?> read(String key) async {
return _channel.invokeMethod<String>('read', {'key': key});
}
Future<void> write(String key, String value) async {
await _channel.invokeMethod<void>('write', {'key': key, 'value': value});
}
}The native implementation must validate arguments, return typed errors, and avoid trusting Dart simply because it is your own client:
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
"read" -> {
val key = call.argument<String>("key")
if (key.isNullOrBlank()) result.error("bad_args", "key required", null)
else result.success(store.read(key))
}
else -> result.notImplemented()
}
}Version the contract if payloads evolve. A channel mismatch in production looks like random MissingPluginException or bad argument crashes because the platform shell and Dart bundle did not move together.
Use pigeon when the contract matters
Hand-written channel serialization is fine for two methods. It becomes brittle as payloads grow. pigeon generates typed bindings for Dart, Kotlin/Java, Swift/Objective-C, and other supported hosts. Generated contracts reduce drift and make nullability explicit. The build cost is worth it for anything security-sensitive or long-lived.
Permissions are workflow state, not booleans
A permission can be denied once, permanently denied, restricted, limited, or irrelevant on a platform. Do not collapse that into allowed too early:
unknown -> request -> granted
unknown -> request -> denied -> explain -> request again?
denied permanently -> open settings -> re-check after resume
limited -> continue with reduced capabilityAlso wire lifecycle re-checks. Users change permissions in system settings while the app is suspended. If your state machine only checks at startup, it will lie.
FFI is for native libraries, not application plumbing
Dart FFI can call C ABI functions directly. It is appropriate for cryptography libraries, decoders, signal processing, or existing native engines. It is not automatically easier than a channel because there is no managed object lifecycle across the boundary. Memory ownership, thread safety, symbol availability, and ABI compatibility become your problem:
final lib = DynamicLibrary.open('libscanner.so');
final scanVersion = lib.lookupFunction<Int32 Function(), int Function()>('scan_version');If you cannot answer who frees memory and on which thread a callback runs, you are not ready to ship the FFI integration.
Abstract the capability, not the operating system
The Dart-facing interface should describe the product capability: SecureStore, LocationSampler, NotificationScheduler. It should not expose Android concepts to iOS or web. Behind the interface, implementations can differ radically. On unsupported platforms, fail explicitly with capability detection rather than pretending success.
Field notes
MissingPluginExceptionoften means the plugin was not registered in the host, a generated registrant is stale, or the test harness lacks platform implementation.- Do not invoke platform channels before the binding is initialized in bootstrap code.
- Plugin compilation failures are often Gradle, Xcode, or SDK version mismatches; read the first native error, not the last Dart red screen.
- Event channels need cancellation and lifecycle handling just like streams.
- Put channel calls behind interfaces so widget tests do not need real platform implementations.
Was this lesson helpful?