前言
有三种方式MethodChannel,BasicMessageChannel,EventChannel
常用的是MethodChannel,Native 端调用需要在主线程中执行
OC
dispatch_async(dispatch_get_main_queue(), ^{
});
swift
DispatchQueue.main.async {
}
内容
要将iOS视图嵌入Flutter需要创建两个类,以下举例
MyFlutterView.swift:写和Flutter通信的方法
MyFlutterViewFactory.swift:绑定Id值
AppDelegate.swift:进行视图的注册
在Flutter中判断设备类型进行视图类型的绑定
static const platform = const MethodChannel('com.flutter.guide.MyFlutterView');
var _data = '获取数据'; //在setState里面调用修改了的值可以及时更新UI显示
var platforms = [];//如果页面有多个原生空间可以使用数组或者字典的方式来获取并通信
...
//创建在iOS中的视图
Widget platformView(){
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidView(
// viewType: 'plugins.flutter.io/custom_platform_view',
// onPlatformViewCreated: (viewId) {
// print('viewId:$viewId');
// platforms
// .add(MethodChannel('com.flutter.guide.MyFlutterView_$viewId'));
// },
// creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
// creationParamsCodec: StandardMessageCodec(),
);
}else if(defaultTargetPlatform == TargetPlatform.iOS){
return UiKitView(
viewType: 'plugins.flutter.io/custom_platform_view',
onPlatformViewCreated: (viewId){
print('viewId:$viewId');
platforms.add(MethodChannel('com.flutter.guide.MyFlutterView_$viewId'));
},
creationParams: {'text': 'Flutter传给IOSTextView的参数'},//向iOS传递初始化参数
creationParamsCodec: StandardMessageCodec(),//将 creationParams 编码后再发送给平台侧
);
}
}
它通过UiKitView中的creationParams参数可在视图初始化的时候将值传递给iOS
也可以通过MethodChannel中的invokeMethod方法将参数传递过去
传递后还可以解析返回值得到回传的数据
var result = await platforms[0].invokeMethod('getData', {'name': 'tqh', 'age': 18});
iOS通过FlutterMethodChannel通过name获取需要响应的视图
let methodChannel = FlutterMethodChannel(name: "com.flutter.guide.MyFlutterView_\(viewID)", binaryMessenger: messenger)
通过setMethodCallHandler方法响应并回传数据
methodChannel.setMethodCallHandler {(call, result:FlutterResult) in
//Flutter传递数据给iOS
if (call.method == "setText") {
if let dict = call.arguments as? Dictionary<String, Any> {
let name:String = dict["name"] as? String ?? ""
let age:Int = dict["age"] as? Int ?? -1
self.label.text = "hello,\(name),年龄:\(age)"
}
}
//Flutter向iOS发起请求,回传数据
else if (call.method == "getData"){
if let dict = call.arguments as? Dictionary<String, Any> {
let name:String = dict["name"] as? String ?? ""
let age:Int = dict["age"] as? Int ?? -1
result(["name":"我是发起请求后得到的\(name)","age":age])
}
}
}