一、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"}
网友评论