MethodChannel 实现flutter 与 原生通信

Posted suiyilaile

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于MethodChannel 实现flutter 与 原生通信的主要内容,如果未能解决你的问题,请参考以下文章