平台通道是Flutter在Dart代码和本机平台代码 (iOS/Android) 之间通信的机制——让Flutter可以访问本机特性或通过Dart包不可用的现有本机代码。它们将Flutter与底层平台连接起来。
平台通道存在的原因
Flutter (Dart) can't directly access every native platform feature. Platform channels
let Dart call NATIVE code (Kotlin/Java on Android, Swift/Objective-C on iOS):
→ access native APIs/SDKs not covered by existing plugins
→ use existing native libraries or platform-specific functionality
→ integrate with native code in a hybrid app
→ The bridge between Flutter and the native platform.
方法通道如何工作
// Dart side: invoke a native method via a MethodChannel
static const platform = MethodChannel('com.example/battery');
Future<int> getBatteryLevel() async {
final int level = await platform.invokeMethod('getBatteryLevel'); // call native
return level;
}
