Flutter 步驟
目的:在flutter頁面中主動調用原生頁面中的方法。
1 在widget中,定義MethodChannel變量
static const MethodChannel methodChannel = MethodChannel("sample.flutter.io/test"); //samples 實際使用可以替換為包名。要跟原生對應即可。
2 通過異步方法調用methodChannel中的invokeMethod方法,指定要調用的activity中的方法
Future<void> _getActivityResult() async { String result; try { final int level = await methodChannel.invokeMethod('getAcivityResult'); //通過getAcivityResult傳遞方法名稱,類似於廣播中的action result = 'getAcivityResult : $level '; } on PlatformException { result = 'Failed to get battery level.'; } setState(() { // _result = result; }); }
Activity 步驟
1 定義channel,與flutter對應
public static String CHANNEL = "sample.flutter.io/test";
2 創建 MethodChannel 並通過 setMethodCallHandler 方法來區分 Flutter 的不同調用方法名和返回對應的回調
new MethodChannel((FlutterView)flutterView,CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) { if(methodCall.equals("getAcivityResult")){ //to do something result.success("success");//回調給flutter的參數 } } });
