Flutter+Android 混合开发MethodChannel的使用

项目的一些网络请求的数据,在原生层都以及实现,现在想把数据在Flutter层展示出来,这里就会用到MethodChannel
第一步:
在原生层注册:

 private MethodChannel methodChannel;//声明

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        methodChannel = new MethodChannel(getFlutterEngine().getDartExecutor(),"com.flutter.io/data");
        //flutterView 通过getFlutterEngine().getDartExecutor()获得
        methodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                if(methodCall.method.equals("getCamera")){

                    Toast.makeText(getApplicationContext(),"getCamera from flutter",Toast.LENGTH_SHORT).show();
                    String  s= "I get your request";
                    result.success(s);
                }

            }
        });

第二步:
flutter层:

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(length: 2, vsync: this);
    platform = const MethodChannel('com.flutter.io/data');
    platform.setMethodCallHandler(methodHandler);

  }
  
  Future methodHandler(MethodCall call) async {
    switch (call.method) {
      case "action1":

        break;
    }
  }

  _getCamera() async {
    String result;
    try {
      result = await platform.invokeMethod('getCamera', "2");
    } on PlatformException catch (e) {
      result = "Failed to  openCamera";
    }
    setState(() {
      print('1111111111111111'+result.toString());
      //将返回的结果展示在flutter层

    });
  }

然后添加一个按钮,调用 _getCamera()函数,就可以实现向方法名 getCamera传相应的参数
总结:

1.flutter端创建一个MethodChannel,名字要和Android端的相同,并使用MethodChannel通过唯一方法名对应调用Android原生方法。
2.Android端同样生成一个MethodChannel,名字要和上步骤Flutter中创建的相同。继承MethodCallHandler方法后实现onMethodCall(MethodCall call, Result result)方法,通过call拿到上步骤调用的唯一方法名实现不同的方法。

发布了7 篇原创文章 · 获赞 1 · 访问量 549

猜你喜欢

转载自blog.csdn.net/Better_WZQ/article/details/103647936