iOS原生和Flutter交互

QQ20201208-150020.gif

一、Flutter调用原生方法

这里我是原生跳转到flutter页面,然后通过点击flutter页面的按钮和原生交互调用原生的返回方法回到原生页面

iOS代码

 // 跳转到Flutter页面
  let flutterVC = FlutterViewController.init()
  flutterVC.setInitialRoute("presentPage")
  flutterVC.modalPresentationStyle = .fullScreen
  self.navigationController?.setNavigationBarHidden(true, animated: true)
        
  self.navigationController?.pushViewController(flutterVC, animated: true)

// 初始化交互通道FlutterMethodChannel
  let presentChannel:FlutterMethodChannel = FlutterMethodChannel.init(name: "sf.flutter.io/sf_present", binaryMessenger: flutterVC as! FlutterBinaryMessenger)


  weak var weakSelf = self
// 添加监听回调
  presentChannel.setMethodCallHandler { (call, result) in
            
            print(call.method)
            print(result)
            // 当flutter调用了原生方法后,此回调会调用
           // call.method 为方法名,call对象里面还有参数属性
            if call.method == "getNativeResult" {
                 weakSelf?.navigationController?.popViewController(animated: true)
                
            }else if call.method == "dismiss" {
                
                print("dismiss")
            }else{
                print(FlutterMethodNotImplemented)
            }
  }

flutter代码

// 交互通道
  static const platform = const MethodChannel('sf.flutter.io/sf_present');

  Future<void> invokeNativeGetResult() async {
    try {
      // 调用原生方法并传参,以及等待原生返回结果数据,getNativeResult是方法名,{"key": "value"}是参数
      var result =
          await platform.invokeListMethod('getNativeResult', {"key": "参数1"});
    } catch (e) {}
  }

当点击某个按钮的时候,调用invokeNativeGetResult函数,通过MethodChannel通道调用对应的原生中的getNativeResult函数,即可。同时也可以携带参数,比如:{"key": "参数1"}

参考:https://www.jianshu.com/p/ca0e47ffef71

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容