MethodChannel 实现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

猜你喜欢

转载自www.cnblogs.com/suiyilaile/p/11038903.html