flutter与Native交互是必不可少的,今天梳理一下,flutter监听native消息
大致流程
- flutter注册EventChannel
- flutter EventChannel监听native消息
- native通过EventChannel发送消息
代码梳理
1 flutter Event监听
const EventChannel("App/Event/Channel", const StandardMethodCodec());
//开始监听
@override
void initState() {
// TODO: implement initState
super.initState();
_eventChannel
.receiveBroadcastStream("init")
.listen(_onEvent, onError: _onError);
}
// 数据接收
void _onEvent(Object value) {
print(value);
}
// 错误处理
void _onError(dynamic) {}
说明:对于receiveBroadcastStream建议添加名称作为native中传递数据的参数使用
2 native 通过Event广播数据
2.1 初始化
FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:@"App/Event/Channel" binaryMessenger:flutterViewController];
[eventChannel setStreamHandler:self];
2.2 数据代理 FlutterStreamHandler
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events {}//此处的arguments可以转化为刚才receiveBroadcastStream("init")的名称,这样我们就可以一个event来监听多个方法实例
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {}
传递数据实例:
#pragma mark - <FlutterStreamHandler>
// // 这个onListen是Flutter端开始监听这个channel时的回调,第二个参数 EventSink是用来传数据的载体。
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
eventSink:(FlutterEventSink)events {
// arguments flutter给native的参数
// 回调给flutter, 建议使用实例指向,因为该block可以使用多次
if (events) {
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setValue:mReferNo forKey:@"ataNo"];
[params setValue:mDocType forKey:@"docType"];
[params setValue:self.aircraftNo forKey:@"aircraftNo"];
// [params setValue:[[NetworkingTools networkHeaders] modelToJSONString] forKey:@"headers"];
// [params setValue:[NetworkingTools networkHeaders] forKey:@"headers"];
[params setValue:@"我是标题" forKey:@"title"];
[params addEntriesFromDictionary:[NetworkingTools networkHeaders] ];
events([params modelToJSONString]);
}
return nil;
}
/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
// arguments flutter给native的参数
return nil;
}
最后是native端调用
FlutterViewController * flutterViewController = [[FlutterViewController alloc] init];
[flutterViewController setInitialRoute:@"App"];
flutterViewController.view.backgroundColor = [UIColor whiteColor];
FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:@"App/Event/Channel" binaryMessenger:flutterViewController];
[eventChannel setStreamHandler:self];
通过以上梳理我们基本就可以进行native反向主动给flutter发送数据
问题踩坑
native发送数据是NSDictionry不要进行内部嵌套:@{@"key":@{}}这样是不通过的
channel命名建议
- Android采用 packagename + eventType + channelname
- iOS 采用 bundleidentifier + event type + channelname
网友评论