MethodChannel 實現flutter 與 原生通信


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的參數
        }
     }
 });

參考 https://www.cnblogs.com/nesger/p/10554146.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM