platform channels主要用来客户端和宿主app之间消息的传递,异步的形式进行传递
调用过程
- Flutter客户端发送消息
- 原生平台接受并返回结果(iOS响应方法:FlutterMethodChannel)(android响应方法:MethodChannel)
具体操作
第一步:Flutter中配置代码触发和接受消息
- MethodChannel配置的参数是唯一的,一般命名规范如下:域名/功能名称
- 使用invokeMethod("方法名称")触发方法
class _TestNativeConnectState extends State<TestNativeConnect> {
// 命名规则:域名/功能(要唯一 )
static const platform1 = const MethodChannel("cy.com/getMessate");
String _nativeMessate = "null";
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Text("获取原生传递数据:${_nativeMessate}"),
RaisedButton(
child: Text("向原生获取数据"),
onPressed: getDataFromNative,
)
],
),
);
}
Future<void> getDataFromNative() async {
final result = await platform1.invokeMethod("getDataFromNative");//挑起方法
setState(() {
_nativeMessate = result;
});
}
}
OC代码:
FlutterViewController *controller = (FlutterViewController*)self.window.rootViewController;
FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"cy.come/getMessate" binaryMessenger:controller.binaryMessenger];
__weak typeof(self) weakSelf = self;
[channel setMethodCallHandler:^(FlutterMethodCall *call,FlutterResult result){
if([@"getDataFromNative" isequalToString:call.method]){
//result([FlutterError errorWithCode:@"5000",message:"错误信息",details:nil]);
result(@"iOS - OC");
}
else{
result(FlutterMethodNotImplemented);
}
}];
第二步:iOS中响应并传递消息
// 获取Flutter ViewController
let controller : FlutterViewController = window.rootViewController! as! FlutterViewController
// 创建FlutterMethodChannel
// 参数一:与flutter中设置的MethodChannel标识对齐 参数二:二进制消息
let channel = FlutterMethodChannel(name: "cy.com/getMessate", binaryMessenger: controller.binaryMessenger)
// 监听channel调用方法
channel.setMethodCallHandler { (call:FlutterMethodCall, result:@escaping FlutterResult) in
guard call.method == "getDataFromNative" else{//判断方法是否实现
result(FlutterMethodNotImplemented);//返回当前方法未实现
return
}
// 返回错误信息
// result(FlutterError(code: "5000", message: "消息不存在", details: nil))
result("iOS")
}
第三步:Android中响应并传递消息
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// 创建methodchannel
val methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger,"cy.com/getMessate");
// 添加回调
methodChannel.setMethodCallHandler{
call, result ->
if (call.method == "getDataFromNative"){
result.success("android")
result.error("5000","抛出异常",null)
}else{
result.notImplemented()
}
}
}