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

  • 相关阅读:
    修改Mysql5.7的root密码
    PHP---练习-----留言板
    PHP----练习------球队列表
    PHP---------ajax
    PHP------Jquery的用法
    PHP-----JSOM类型数据
    PHP-------- JQUERY方式
    PHP-------PDO:数据访问抽象层
    PHP-----练习-------租房子-----增删改查,多条件查询
    PHP------练习------投票
  • 原文地址:https://www.cnblogs.com/suiyilaile/p/11038903.html
Copyright © 2011-2022 走看看