Flutter与iOS混合开发(flutter原生混合开发)
1、Flutter、iOS原生通讯
1.1、Flutter发送句柄
Flutter创建句柄:
MethodChannel _methodChannel = MethodChannel('channelKey');复制代码
发送句柄内容:(arguments为可选)
_methodChannel.invokeMapMethod('sendIOSKey');复制代码
1.2、Flutter接收句柄
接收句柄内容
_methodChannel.setChannelCallHandler((call){ if(call.method == 'sendFlutterKey') { print(call.arguments); } });复制代码
1.3、iOS发送句柄
iOS创建句柄:
MethodChannelWithName: binaryMessenger:
FlutterMethodChannel *methodChannel = [FlutterMethodChannel MethodChannelWithName:'channelKey' binaryMessenger:flutterVC.binaryMessenger];复制代码
发送句柄内容:
[methodChannel invokeMethod:"sendFlutterKey" arguments:发送内容];复制代码
1.4、iOS接收句柄
接收句柄内容:
[methodChannel setMethodCallHandler:^(FlutterMethodCall * call,FlutterResult result){ if([call.method isEqualToString:'sendIOSKey']){ } }];复制代码
注意:
Flutter和iOS双向创建channel,key名对上则连接建立
Flutter发送句柄内容arguments为可选项,iOS发送句柄内容arguments为显式
接收Channel调用
call
,参数为.method
和.arguments
2、iOS项目嵌入Flutter页面
2.1、Podfile配置
2.2、setInitialRoute:
(Flutter不建议使用、内存爆炸)
2.2.1、iOS中调起Flutter界面
[flutterVC setInitialRoute:"key"];
window.defaultRouteName
:在Flutter的MyApp()中调用iOS传的Route参数'key'
2.2.2、Flutter操作后回调iOS
使用Flutter引擎操作
通过
initWithEngine:
创建flutterVC,缺点不能向Flutter传参,使
setInitialRoute:
失效优点内存不爆
3、Channel三种类型
3.1、MethodChannel
传递方法调用
3.2、BasicMessageChannel
持续通讯,收到消息后还能回复消息
Flutter创建BasicMessageChannel:BasicMessageChannel _msgChannel =
BasicMessageChannel('channelKey',StandardMessageCodec());
StandardMessageCodec():编解码器,必传
发送内容:
_msgChannel.send(发送内容);
iOS创建BasicMessageChannel:BasicMessageChannel _msgChannel =
[FlutterBasicChannel messageChannelWithName:"channelKey" binaryMessenger:_flutterVC.binaryMessenger]
;发送内容:
[_msgChannel sendMessage:发送内容];
3.3、EventChannel
数据流
注意:
Flutter代码修改后,有时需要
command+shift+k
清理缓存在运行才能看到改变,有时则需要先在AS里运行iOS创建的是Flutter引擎(一个没有层级的Flutter界面)
伪原创工具 SEO网站优化 https://www.237it.com/
作者:晓之卫
链接:https://juejin.cn/post/7035807333930237982