方法通道
在 Android 中是通過 FlutterView,而在 iOS 中則是通過 FlutterViewController 進(jìn)行注冊(cè)的。FlutterView 與 FlutterViewController 為 Flutter 應(yīng)用提供了一個(gè)畫板,使得構(gòu)建于 Skia 之上的 Flutter 通過繪制即可實(shí)現(xiàn)整個(gè)應(yīng)用所需的視覺效果。
Flutter 代碼
const platform =MethodChannel('samples.chenhang/navigation');// 聲明 MethodChannel
class DefaultPage extends StatelessWidget {
DefaultPage({Key? key}) :super(key: key);
String _nativeCallBackValue ='等待原生傳值';
//異步執(zhí)行調(diào)用原生方法,保持頁面不卡住,因?yàn)檎{(diào)用原生的方法可能沒實(shí)現(xiàn)會(huì)拋出異常,所以trycatch包住
? Future_communicateFunction(flutterPara)async {
try {
//原生方法名為callNativeMethond,flutterPara為flutter調(diào)用原生方法傳入的參數(shù),await等待方法執(zhí)行
? ? ? final result =await platform.invokeMethod(
'callNativeMethond', flutterPara);
//如果原生方法執(zhí)行回調(diào)傳值給flutter,那下面的代碼才會(huì)被執(zhí)行
? ? ? _nativeCallBackValue =result;
print("----$_nativeCallBackValue");
? ? }on PlatformException catch (e) {
//拋出異常
//flutter: PlatformException(001, 進(jìn)入異常處理, 進(jìn)入flutter的trycatch方法的catch方法)
? ? ? print("----$e");
}
}
@override
? Widget build(BuildContext context) {
return Scaffold(
backgroundColor:Colors.yellowAccent,
appBar:AppBar(title:Text("Default Page")),
body:Center(
child:
RaisedButton(child:Text("打開應(yīng)用商店"), onPressed: () {
_communicateFunction({"type":"221133"});
// platform.invokeMethod('callNativeMethond');
? ? ? ? ? })),
);
}
}
iOS端代碼?
在 iOS 平臺(tái),方法調(diào)用的處理和響應(yīng)是在 Flutter 應(yīng)用的入口,也就是在 Applegate 中的 rootViewController(即 FlutterViewController)里實(shí)現(xiàn)的,因此我們需要打開 Flutter 的 iOS 宿主 App,找到 AppDelegate.m 文件,并添加相關(guān)邏輯。
override func application(
_ application:UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) ->Bool {
GeneratedPluginRegistrant.register(with:self)
let controller = self.window.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel.init(name: "samples.chenhang/navigation", binaryMessenger: controller as! FlutterBinaryMessenger)
channel.setMethodCallHandler { (call, result) in
if call.method == "callNativeMethond" {
letstr ="itms-apps://itunes.apple.com/xy/app/foo/id414478124"
? ? ? ? ? ? guard leturl = URL(string: str)else {return }
letcan = UIApplication.shared.canOpenURL(url)
ifcan {
if #available(iOS 10.0,*) {
UIApplication.shared.open(url, options: [:]) { (b)in
? ? ? ? ? ? ? ? ? ? ? ? print("打開結(jié)果: \(b)")
}
}else {
//iOS 10 以前
UIApplication.shared.openURL(url)
}
}
result("我是原生返回?cái)?shù)據(jù)----")
print("111111")
letpara = call.arguments
? ? ? ? ? ? ? ? print("------\(para!)")
}else{
print("22222222")
result(FlutterMethodNotImplemented)
}
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Android端 代碼??在 Android 平臺(tái),方法調(diào)用的處理和響應(yīng)是在 Flutter 應(yīng)用的入口,也就是在 MainActivity 中的 FlutterView 里實(shí)現(xiàn)的,因此我們需要打開 Flutter 的 Android 宿主 App,找到 MainActivity.java 文件,并在其中添加相關(guān)的邏輯。
android/app/src/main/java/com/example/MainActivity.java 文件
//import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class MainActivityextends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//? ? ? ? GeneratedPluginRegistrant.registerWith(this);
? ? ? ? new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(),"samples.chenhang/navigation").setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
// Note: this method is invoked on the main thread.
? ? ? ? ? ? ? ? ? ? ? ? if(call.method.equals("callNativeMethond")) {
try {
Uri uri = Uri.parse("market://details?id=com.tencent.mm");
Intent intent =new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}catch (Exception e) {
//? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? result.error("UNAVAILABLE", "沒有安裝應(yīng)用市場(chǎng)", null);
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
Log.e("MainActivity","Flutter -> Android 回調(diào)內(nèi)容:" + call.arguments.toString());
? ? ? ? ? ? ? ? ? ? ? ? ? ? result.success("Android -> Flutter 接收回調(diào)后返回值:" +"Na收到指令");
}
else {
result.notImplemented();
}
}
});
}
}