美文网首页
Flutter 项目使用MethodChannel撰写双端平台代

Flutter 项目使用MethodChannel撰写双端平台代

作者: 大虾啊啊啊 | 来源:发表于2023-06-25 10:50 被阅读0次

一、简介

Flutter 作为一个跨平台UI框架,很多原生的功能无法实现,因此我们可以在Flutter中和其他平台通信调用对应平台的能力,在Flutter 中使用MethodChannel编写双端代码,相互通信,本文以Android为例,其他各个平台参考官网
https://flutter.cn/docs/packages-and-plugins/developing-packages

二、实现

1、定义平台通信唯一通道

  private val CHANNEL = "samples.flutter.dev/battery"

2、编写Android代码

package com.example.batterylevel

import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val CHANNEL = "samples.flutter.dev/battery"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
        //设置dart调用kotlin的函数监听
        channel.setMethodCallHandler {
            // This method is invoked on the main thread.
                call, result ->
            if (call.method == "getBatteryLevelFromAndroid") {
                val args = mapOf("batteryLevel" to "999")
                //在android又调用dart中的函数
                channel.invokeMethod(
                    "getBatteryLevelFromDart",
                    args,
                    object : MethodChannel.Result {
                        override fun success(value: Any?) {
                            //设置结果
                            result.success("value is ${value}")
                        }

                        override fun error(
                            errorCode: String,
                            errorMessage: String?,
                            errorDetails: Any?
                        ) {
                        }

                        override fun notImplemented() {
                        }

                    })
                //  result.success("11111111111")
            } else {
                result.notImplemented()
            }
        }


    }


}

3、编写flutter代码

相关文章

网友评论

      本文标题:Flutter 项目使用MethodChannel撰写双端平台代

      本文链接:https://www.haomeiwen.com/subject/dmeiydtx.html