Flutter.2.Flutter与OC的双向调用

Flutter与OC 的双向调用

一. flutter调用OC

OC注册方法

FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"mrliuys.flutter.io/channel" binaryMessenger:flutterViewController];

__weak typeof(self) weakSelf = self;
    
[channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
    NSLog(@"%@-%@",call.method, call.arguments);    
    if ([@"FlutterTransferNative" isEqualToString:call.method]) {    
        NSLog(@"FlutterTransferNative-%@", call.arguments);      
    }
    else {
        result(FlutterMethodNotImplemented);
    }
}];

flutterViewController 在上一篇已经已创建过,接在后面就可以

flutter调用方法

static const channel = const MethodChannel('mrliuys.flutter.io/channel');
/*
flutter调用原生方法
*/
Future _flutterTransferNative() async {
    try{
      //调用原生
      await channel.invokeMethod('FlutterTransferNative',{
        'key1':'obj1',
        'key2':'obj2'
      });
    }on PlatformException catch(e){

    }
}

mrliuys.flutter.io/channel这个是自由定义,且是全局唯一的,

当flutter需要用到的时候执行invokeMethod,
invokeMethod带两个参数.

  1. 方法名,方法名不能为空
  2. 数据,数据可以为空

二. OC调用flutter

flutter注册方法

class HelloMyApp extends StatelessWidget {
  static const channel = const MethodChannel('mrliuys.flutter.io/channel');
  ...
  @override
  Widget build(BuildContext context) {
    ...
    /*
    注册: 原生调用flutter
     */
    channel.setMethodCallHandler((MethodCall call) async {
      if(call.method == 'nativeTransferFlutter') {
        return(call.arguments);
      }
    });
    ...
  }
}

OC调用

FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"mrliuys.flutter.io/channel" binaryMessenger:flutterViewController];
//延时调用
[[[RACSignal interval:3 onScheduler:[RACScheduler scheduler]]takeUntil:self.rac_willDeallocSignal ] subscribeNext:^(id x) {
    
    [channel invokeMethod:@"nativeTransferFlutter" arguments:@{@"key1":@"obj1",
                                                               @"key2":@"obj2"
                                                               }
                   result:^(id  _Nullable result) {
                       //flutter回调信息
                       NSLog(@"%@",result);
                   }];
}];

你可能感兴趣的:(Flutter.2.Flutter与OC的双向调用)