IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Flutter框架分析-MethodChannel -> 正文阅读

[移动开发]Flutter框架分析-MethodChannel

1.?前言

在文章Flutter框架分析(八)-Platform Channel中,我们分析了MethodChannel的原理和结构,并详细讲解了与其相关的一些核心类,例如MethodCallHandlerMethodCodec等,本文主要讲解使用MethodChannel的示例。

2.?使用流程

MethodChannel可用于Flutter调用native的方法,也可用于native调用Flutter的方法,所以接下来将分别分析这两种使用流程。

2.1 ?Flutter调用native方法

流程如下:

1)native端创建某channel name的MethodChannel

2)native端使用setMethodCallHandler函数,设置该MethodChannelMethodCallHandler

3)Flutter端创建该channel name的MethodChannel

4)Flutter端使用该MethodChannel通过invokeMethod函数向native端发送方法调用,传递参数为方法名和方法参数。

5)native端刚刚注册的MethodCallHandler收到发送的消息,在onMethodCall中处理消息,通过reply函数进行回复。

6)Flutter端处理该回复。

Flutter端关键代码如下:

class?_MyHomePageState?extends?State<MethodChannelWidget> {
??static const?nativeChannel =?const?MethodChannel('flutter2/MethodChannel');
??int?_counter?=?0;

??void?_incrementCounter()?async?{
????setState(() {
??????_counter++;
????});
????String result?=?await?nativeChannel.invokeMethod('getJavaMethod',?"123");
????print('methodChannelTest _incrementCounter: +?$result');
??}

??@override
??Widget?build(BuildContext?context) {
????return?Scaffold(
??????appBar:?AppBar(
????????title:?Text("method channel test"),
??????),
??????body:?Center(
      child:?Column(
??????????mainAxisAlignment:?MainAxisAlignment.center,
??????????children: <Widget>[
????????????Text(
??????????????'You have pushed the button this many times:',
????????????),
????????????Text(
??????????????'$_counter',
??????????????style:?Theme.of(context).textTheme.headline4,
????????????),
??????????],
????????),
??????),
??????floatingActionButton:?FloatingActionButton(
????????onPressed: _incrementCounter,
????????tooltip:?'Increment',
????????child:?Icon(Icons.add),
??????),? // This trailing comma makes auto-formatting nicer for build methods.
   );
??}
}

native端关键代码如下:

class MethodChannelActivity : FlutterActivity() {
    private var mFlutter2MethodChannel: MethodChannel? = null

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        Log.d("FirstNativeActivity", "configureFlutterEngine")
        initChannel(flutterEngine)
    }

    private fun initChannel(flutter2Engine: FlutterEngine) {
        mFlutter2MethodChannel = MethodChannel(flutter2Engine.dartExecutor, "flutter2/MethodChannel")
        mFlutter2MethodChannel!!.setMethodCallHandler(MethodCallHandler  {call, result ->
        Log.e("methodChannelTest", "onMethodCall method:" + call.method)
            if ("getJavaMethod" == call.method) {
                result.success("success ")
                Log.e("methodChannelTest", "success:" + call.arguments())
            } else {
                result.success(" unKnow method")
            }
         })
    }

    companion object {
        fun startActivity(activity: Activity) {
            val intent = Intent(activity, MethodChannelActivity::class.java)
            activity.startActivity(intent)
        }
    }
}

2.2 ?native调用Flutter端方法

流程如下:

1)?Flutter端创建channel name的MethodChannel

2)?Flutter端使用setMethodCallHandler函数,设置该MethodChannelHandler函数。

3)?native端创建某channel name的MethodChannel

4)?native端使用该MethodChannel通过invokeMethod函数向Flutter端发送消息,传递参数为方法名和方法参数。

5)?Flutter端刚刚注册的Handler收到发送的消息,并处理消息,然后通过reply函数进行回复。

6)?native端处理该回复。

Flutter端关键代码如下:

class?_MyHomePageState?extends?State<MethodChannelWidget> {
??static const?nativeChannel =?const?MethodChannel('flutter2/MethodChannel');
??int?_counter?=?0;

??@override
??void?initState() {
????nativeChannel.setMethodCallHandler(flutterMethod);
????super.initState();
??}

??Future<dynamic>?flutterMethod(MethodCall?methodCall)?async?{
????switch?(methodCall.method) {
??????case?'flutterMethod':
????????print('methodChannelTest 原生Android调用了flutterMethod方法 参数是:'+methodCall.arguments);
????????return?"hahaha";
????}
??}
}

native端关键代码如下:

class MethodChannelActivity : FlutterActivity() {
    private var mFlutter2MethodChannel: MethodChannel? = null
    private var mHandler: Handler? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mHandler = Handler()
        mHandler!!.postDelayed( {
        Log.e("methodChannelTest", "getJavaMethod invokeFlutterMethod_toAllFlutter")
            invokeFlutterMethod_toAllFlutter()
         } , 3000)
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        Log.d("FirstNativeActivity", "configureFlutterEngine")
        initChannel(flutterEngine)
    }

    private fun initChannel(flutter2Engine: FlutterEngine) {
        mFlutter2MethodChannel = MethodChannel(flutter2Engine.dartExecutor, "flutter2/MethodChannel")
    }

    private fun invokeFlutterMethod_toAllFlutter() {
        if (mFlutter2MethodChannel != null) {
            mFlutter2MethodChannel!!.invokeMethod("flutterMethod", "我是原生Android,我将参数传递给Flutter里面的一个方法", object : MethodChannel.Result {
                override fun success(o: Any?) {
                    Log.d("methodChannelTest", "flutterMethod:$o")
                }

                override fun error(s: String, s1: String?, o: Any?) {}
                override fun notImplemented() {}
            })
        }
    }

    companion object {
        fun startActivity(activity: Activity) {
            val intent = Intent(activity, MethodChannelActivity::class.java)
            activity.startActivity(intent)
        }
    }
}

3. 小结

本文主要介绍了MethodChannel的使用流程,并列举了一个使用MethodChannel的示例。

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-08-11 12:31:59  更:2021-08-11 12:32:30 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 8:18:27-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码