flutter代碼
class _MyHomePageState extends State<MyHomePage> {
String _nativeCallBackValue = '等待原生傳值';
//交互的通道名稱草冈,flutter和native是通過這個(gè)標(biāo)識(shí)符進(jìn)行相互間的通信
static const communicateChannel = MethodChannel('https://www.oyear.cn');
//異步執(zhí)行調(diào)用原生方法厂画,保持頁面不卡住,因?yàn)檎{(diào)用原生的方法可能沒實(shí)現(xiàn)會(huì)拋出異常别惦,所以trycatch包住
Future<void> _communicateFunction(flutterPara) async {
try {
//原生方法名為callNativeMethond,flutterPara為flutter調(diào)用原生方法傳入的參數(shù)月培,await等待方法執(zhí)行
final result = await communicateChannel.invokeMethod(
'callNativeMethond', flutterPara);
//如果原生方法執(zhí)行回調(diào)傳值給flutter好渠,那下面的代碼才會(huì)被執(zhí)行
_nativeCallBackValue = result;
setState(() {});
} on PlatformException catch (e) {
//拋出異常
//flutter: PlatformException(001, 進(jìn)入異常處理, 進(jìn)入flutter的trycatch方法的catch方法)
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView(
children: <Widget>[
InkWell(
onTap: () {
_communicateFunction({"type": "221133"});
},
child: Container(child: Text("與原生交互"))),
Container(child: Text(_nativeCallBackValue))
],
));
}
}
swift代碼
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let controller = self.window.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel.init(name: "https://www.oyear.cn", binaryMessenger: controller as! FlutterBinaryMessenger)
channel.setMethodCallHandler { (call, result) in
if call.method == "callNativeMethond" {
let para = call.arguments
print(para!)
result("我是原生返回?cái)?shù)據(jù)")
}else{
result(FlutterMethodNotImplemented)
}
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}