
QQ20201208-150020.gif
一、Flutter調(diào)用原生方法
這里我是原生跳轉(zhuǎn)到flutter頁(yè)面,然后通過(guò)點(diǎn)擊flutter頁(yè)面的按鈕和原生交互調(diào)用原生的返回方法回到原生頁(yè)面
iOS代碼
// 跳轉(zhuǎn)到Flutter頁(yè)面
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
// 添加監(jiān)聽(tīng)回調(diào)
presentChannel.setMethodCallHandler { (call, result) in
print(call.method)
print(result)
// 當(dāng)flutter調(diào)用了原生方法后,此回調(diào)會(huì)調(diào)用
// call.method 為方法名,call對(duì)象里面還有參數(shù)屬性
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 {
// 調(diào)用原生方法并傳參,以及等待原生返回結(jié)果數(shù)據(jù),getNativeResult是方法名,{"key": "value"}是參數(shù)
var result =
await platform.invokeListMethod('getNativeResult', {"key": "參數(shù)1"});
} catch (e) {}
}
當(dāng)點(diǎn)擊某個(gè)按鈕的時(shí)候,調(diào)用invokeNativeGetResult函數(shù),通過(guò)MethodChannel通道調(diào)用對(duì)應(yīng)的原生中的getNativeResult函數(shù),即可。同時(shí)也可以攜帶參數(shù),比如:{"key": "參數(shù)1"}