在 Flutter 中,与原生(Android / iOS)交互主要通过 Platform Channel 实现。下面从原理、方式、示例几个层面说明。
Flutter 与原生不在同一线程、不同语言环境,通信通过 异步消息通道。
三种常用 Channel:
| 类型 | 用途 |
|---|---|
MethodChannel |
一次性方法调用(最常用) |
EventChannel |
原生向 Flutter 持续发送事件(如传感器) |
BasicMessageChannel |
双向、结构化消息通信 |
import 'package:flutter/services.dart';
const platform = MethodChannel('com.example/app');
Future<void> getBatteryLevel() async {
try {
final int result = await platform.invokeMethod('getBatteryLevel');
print('电池电量: $result%');
} on PlatformException catch (e) {
print("失败: ${e.message}");
}
}
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"com.example/app"
).setMethodCallHandler { call, result ->
if (call.method == "getBatteryLevel") {
val level = 80
result.success(level)
} else {
result.notImplemented()
}
}
}
}
import Flutter
class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller = window?.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel(
name: "com.example/app",
binaryMessenger: controller.binaryMessenger
)
channel.setMethodCallHandler { call, result in
if call.method == "getBatteryLevel" {
result(85)
} else {
result(FlutterMethodNotImplemented)
}
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
platform.setMethodCallHandler((call) async {
if (call.method == "fromNative") {
print(call.arguments);
}
});
原生调用:
channel.invokeMethod("fromNative", "Hello from Android")
适合:
Flutter
EventChannel('com.example/events')
.receiveBroadcastStream()
.listen((event) {
print(event);
});
dev_dependencies:
pigeon: ^x.x.x
如果你告诉我:
我可以直接给你完整可运行示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。