为 iOS 和 Android 编写自定义平台插件
编写联合插件,将原生 Kotlin 和 Swift API 暴露给 Dart。
为 iOS 和 Android 编写自定义平台插件 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flutter Mobile Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flutter Mobile Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Platform Plugins?
Dart cannot call native iOS or Android APIs directly. A platform plugin bridges that gap, exposing Swift/Objective-C and Kotlin/Java capabilities to your Dart code through a typed channel.
- Package: pure Dart, no native code.
- Plugin: Dart API plus platform-specific native implementations.
You write a plugin whenever you need hardware (sensors, BLE), OS services (notifications, keychain), or a native SDK that has no Dart equivalent. In this lesson we author a federated plugin that surfaces native Kotlin and Swift APIs to Dart.
Federated Plugin Architecture
A federated plugin splits responsibilities across several packages so different parties can own different platforms:
- app-facing package (
battery): the public Dart API developers import. - platform interface (
battery_platform_interface): an abstract contract all implementations must satisfy. - platform packages (
battery_android,battery_ios): concrete native implementations registered viapubspec.yaml.
This decoupling lets a third party add, say, a Windows implementation without touching the app-facing package. The interface package is the linchpin contract.
The Platform Interface Contract
The platform interface uses the plugin_platform_interface package. It declares an abstract base class with a MethodChannel-free contract, plus a default instance other packages override.
The PlatformInterface token-verification prevents implementers from extends-ing and breaking the contract; they must use implements guarded by verifyToken.
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
abstract class BatteryPlatform extends PlatformInterface {
BatteryPlatform() : super(token: _token);
static final Object _token = Object();
static BatteryPlatform _instance = MethodChannelBattery();
static BatteryPlatform get instance => _instance;
static set instance(BatteryPlatform value) {
PlatformInterface.verifyToken(value, _token);
_instance = value;
}
Future<int> getBatteryLevel() {
throw UnimplementedError('getBatteryLevel() is not implemented.');
}
}MethodChannel: The Default Implementation
The default implementation talks to native code over a MethodChannel. Each channel has a unique name shared by Dart and native sides. invokeMethod serializes arguments using the standard message codec and awaits a native reply.
Keep channel names namespaced (reverse-DNS) to avoid collisions across plugins.
import 'package:flutter/services.dart';
import 'battery_platform_interface.dart';
class MethodChannelBattery extends BatteryPlatform {
final MethodChannel _channel =
const MethodChannel('com.example.battery/methods');
@override
Future<int> getBatteryLevel() async {
final level = await _channel.invokeMethod<int>('getBatteryLevel');
if (level == null) {
throw PlatformException(code: 'NO_LEVEL', message: 'Level unavailable');
}
return level;
}
}Android: Kotlin Plugin Registration
On Android the native side implements FlutterPlugin and MethodChannel.MethodCallHandler. In onAttachedToEngine you wire a MethodChannel with the same name used in Dart, then route incoming calls in onMethodCall.
result.success(value)resolves the Dart Future.result.error(code, msg, details)throws aPlatformExceptionin Dart.result.notImplemented()signals an unknown method.
This is Kotlin, not Dart, so it is illustrative only.
iOS: Swift Plugin Registration
On iOS you conform to FlutterPlugin and register in register(with:), creating a FlutterMethodChannel with the matching name. handle(_:result:) dispatches calls and replies via the FlutterResult callback.
For federated plugins the platform package declares its native entry point under flutter.plugin.platforms.ios in pubspec.yaml, pointing at the Swift class. The Dart registrant is wired automatically.
Declaring the Federated pubspec
The platform implementation packages announce themselves via flutter.plugin.platforms. The dartPluginClass is registered with the platform interface at startup, and pluginClass names the native class.
Crucially the app-facing package lists each platform package under default_package, so adding a platform is a pubspec change, not a code change.
Endorsing Platform Implementations
The app-facing package endorses implementations by depending on them in its pubspec.yaml. Endorsed packages are pulled in transitively, so app developers add one dependency and get every platform.
At runtime, each platform package's registerWith() sets the interface's instance to its own implementation. The Dart API then calls through BatteryPlatform.instance without knowing which platform answered.
// battery_android registers itself at startup
import 'battery_platform_interface.dart';
class BatteryAndroid extends BatteryPlatform {
/// Registered via dartPluginClass in pubspec.yaml.
static void registerWith() {
BatteryPlatform.instance = BatteryAndroid();
}
@override
Future<int> getBatteryLevel() {
// Delegates to the MethodChannel under the hood.
return MethodChannelBattery().getBatteryLevel();
}
}The App-Facing Dart API
The public package wraps the interface in an ergonomic, well-documented API. App developers never touch channels or platform classes — they call clean Dart methods.
Keep this layer thin: validation, convenience overloads, and documentation. All real work lives behind BatteryPlatform.instance.
import 'battery_platform_interface.dart';
class Battery {
/// Returns the current battery level as a percentage (0-100).
Future<int> get batteryLevel => BatteryPlatform.instance.getBatteryLevel();
/// Convenience: true when the device is critically low.
Future<bool> get isCritical async => (await batteryLevel) <= 15;
}Streaming Native Events with EventChannel
For continuous data (charging state, sensor streams) a single method call is not enough. Use an EventChannel: the native side pushes events through a StreamHandler/FlutterEventSink, and Dart exposes them as a Stream.
receiveBroadcastStream lazily starts the native listener on first subscription and tears it down on cancel.
import 'package:flutter/services.dart';
class BatteryStream {
final EventChannel _events =
const EventChannel('com.example.battery/charging');
Stream<bool> get onChargingChanged => _events
.receiveBroadcastStream()
.map((event) => event == 'charging');
}Type-Safe Channels with Pigeon
Hand-written channels are stringly-typed and error-prone. Pigeon generates type-safe Dart, Kotlin, and Swift bindings from a single Dart definition file, eliminating method-name typos and codec mismatches.
You annotate an abstract class with @HostApi() (Dart calls native) or @FlutterApi() (native calls Dart), run the Pigeon generator, and wire the generated classes — no manual invokeMethod strings.
import 'package:pigeon/pigeon.dart';
class BatteryInfo {
int? level;
bool? isCharging;
}
@HostApi()
abstract class BatteryHostApi {
BatteryInfo getBatteryInfo();
}
@FlutterApi()
abstract class BatteryFlutterApi {
void onLevelChanged(int level);
}Quick Check
You are publishing a Flutter plugin and want third parties to add new platform implementations (e.g. Windows) without modifying or forking your app-facing package. Which architecture and mechanism makes that possible?
Recap
You learned to author a federated platform plugin exposing native Kotlin and Swift APIs to Dart:
- Architecture: app-facing package, platform interface, and per-platform implementations.
- Contract: an abstract
PlatformInterfacewith token verification and a swappableinstance. - Channels:
MethodChannelfor request/response,EventChannelfor native event streams, with matching names on both sides. - Native sides: Kotlin
onMethodCalland Swifthandle(_:result:)resolving via success/error. - Endorsement: pubspec wires
dartPluginClassandpluginClassso platforms register themselves. - Pigeon: generates type-safe bindings to replace fragile string-based channels.
With this you can wrap any native SDK behind a clean, testable Dart API.
常见问题解答
「为 iOS 和 Android 编写自定义平台插件」课时是免费的吗?
是的 — 「为 iOS 和 Android 编写自定义平台插件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。
「为 iOS 和 Android 编写自定义平台插件」这节课中我会学到什么?
编写联合插件,将原生 Kotlin 和 Swift API 暴露给 Dart。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flutter Mobile Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「为 iOS 和 Android 编写自定义平台插件」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flutter Mobile Development 课中编写并运行代码吗?
能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 dart:ffi 调用 C 库
- 类型安全的平台通道与 Pigeon
- 为 iOS 和 Android 编写自定义平台插件
- 后台隔离区与原生内存管理