三种主要通信方式
- MethodChannel:与原生相互进行方法调用,用于方法调用(双向)
- BasicMessageChannel:与原生相互发送消息,用于数据传输(双向)
- EventChannel:原生发送消息,Flutter接收,用于数据流通信(单向)
具体实现
1. MethodChannel
使用方式以及交互流程,请查看截图中代码以及注释OC初始化相关代码
@interface ViewController ()<FlutterStreamHandler> @property(strong, nonatomic) NSTimer *timer; @property(strong, nonatomic) FlutterEngine *flutterEngine; @property(strong, nonatomic) FlutterViewController *flutterVC; @property(strong, nonatomic) FlutterBasicMessageChannel *basicMessageChannel; @property(strong, nonatomic) FlutterEventChannel *eventChannel; @property(copy, nonatomic) FlutterEventSink eventSink; @end
OC懒加载相关代码
- (FlutterEngine *)flutterEngine { if (!_flutterEngine) { FlutterEngine *engine = [[FlutterEngine alloc] init]; if (engine.run) { _flutterEngine = engine; } } return _flutterEngine; } - (FlutterViewController *)flutterVC { if (!_flutterVC) { _flutterVC = [[FlutterViewController alloc] initWithEngine:self.flutterEngine nibName:nil bundle:nil]; } return _flutterVC; } - (FlutterBasicMessageChannel *)basicMessageChannel { if (!_basicMessageChannel) { //注册FlutterBasicMessageChannel - 并指定名称messageChannelName为basicMessageChannel _basicMessageChannel = [FlutterBasicMessageChannel messageChannelWithName:@"basicMessageChannel" binaryMessenger:self.flutterVC.binaryMessenger]; //监听Flutter发来的消息 - Flutter调用OC回调监听 [_basicMessageChannel setMessageHandler:^(id _Nullable message, FlutterReply _Nonnull callback) { NSLog(@"OC收到Flutter的FlutterBasicMessageChannel - %@", message); }]; } return _basicMessageChannel; } - (FlutterEventChannel *)eventChannel { if (!_eventChannel) { _eventChannel = [FlutterEventChannel eventChannelWithName:@"eventChannel" binaryMessenger:self.flutterVC.binaryMessenger]; [_eventChannel setStreamHandler:self]; } return _eventChannel; }
2. BasicMessageChannel
使用方式以及交互流程,请查看截图中代码以及注释3. EventChannel使用方式以及交互流程,请查看截图中代码以及注释运行结果
flutter: 消息内容: OC通过EventChannel向Flutter发送消息(OC参数类型是id), Flutter收到消息数据类型: String
完整代码(github中Flt文件夹里面的内容):
https://github.com/gltwy/public