zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    sql number类型和varchar2类型
    B
    E
    D
    B
    A
    第三课 选区
    第二课 新建文件与图层
    第一课 界面认识
    CSS命名规则
  • 原文地址:https://www.cnblogs.com/suiyilaile/p/11038903.html
Copyright © 2011-2022 走看看