flutter 三种原生交互

MethodChannel:方法调用

ios端初始化,指定和flutter对接的路由:

  FlutterMethodChannel *methodChannel = [FlutterMethodChannel methodChannelWithName:@"one_page" binaryMessenger:self.flutterVC.binaryMessenger];

调用flutter方法:[methodChannel invokeMethod:@"one" arguments:@""];

 设置句柄,flutter调用ios原生方法 [methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {

if ([call.method isEqualToString:@"exit"]) {

            [self.flutterVC dismissViewControllerAnimated:YES completion:^{
               }];

              [abc invokeMethod:@"three" arguments:@""];

        }

    }];

flutter端初始化,指定和ios对接的路由 final MethodChannel _oneChannel = MethodChannel('one_page');
flutter端调用:exit方法名,arg参数 channel.invokeMethod('exit', 'arg');

 

baseChannel:消息传递

ios端的方法实现和调用:

    FlutterBasicMessageChannel *baseChannel = [FlutterBasicMessageChannel messageChannelWithName:@"BasicChannel_one" binaryMessenger:self.flutterVC.binaryMessenger];

//    [baseChannel sendMessage:@"BasicChannel_one sendMessage"];

//    [baseChannel sendMessage:@"BasicChannel_one sendMessage callBack" reply:^(id  _Nullable reply) {

//        NSLog(@"BasicChannel_one  reply: %@",reply);

//    }];

    [baseChannel setMessageHandler:^(id  _Nullable message, FlutterReply  _Nonnull callback) {

        NSLog(@"BasicChannel_one : message :%@ \n callBack: %@",message,callback);

        [baseChannel sendMessage:@[@"123",@"456"]];

    }];

flutter端的实现和调用:

//  final BasicMessageChannel _basicMessageChannel_one = BasicMessageChannel(
//      'BasicChannel_one', StandardMessageCodec());

StandardMessageCodec是flutter端的解析方式,默认的就是这个方式

channel.send('aaa') 发送消息

 

 

eventChannel:算是事件监听

和上面两种有点不同,上面是拿到channel调用方法或者发送消息,eventChannel需要实现Delegate--FlutterStreamHandler

实现方法:

-(FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events{

    self.eventSink = events;

//拿到eventSink 就可以随时发送数据了。eventSink是个block

    self.eventSink([NSString stringWithFormat:@"%ld", self.number++]);

    

    NSLog(@"接收到的值: %@",arguments);

    return nil;

}

-(FlutterError *)onCancelWithArguments:(id)arguments{

    

    return nil;

}

eventChannel的声明:

FlutterEventChannel *eventChannel_one= [FlutterEventChannel eventChannelWithName:@"eventChannel_one" binaryMessenger:self.flutterVC.binaryMessenger];

                [eventChannel_one setStreamHandler:self];

flutter端的声明和调用:

_eventChannel.receiveBroadcastStream('receiveBroadcastStream').listen((value) {
  print('接受的值 $value');
}, onError: (error) {
  print('发生错误');
}, onDone: () {
  print('监听结束');
}, cancelOnError: true);

//receiveBroadcastStream 为发送到NA端的值,value为接受的值

你可能感兴趣的:(flutter 三种原生交互)