前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 BasicMessageChannel 通信 )

【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 BasicMessageChannel 通信 )

作者头像
韩曙亮
发布2023-03-29 15:53:32
2.9K0
发布2023-03-29 15:53:32
举报
文章被收录于专栏:韩曙亮的移动开发专栏

文章目录

一、BasicMessageChannel 简介


BasicMessageChannel 简介 :

这是一个命名通道 , 用于 Flutter 端 与 Native 端的消息传递 ;

发送消息前 , 先编码成二进制信息 , 接收后再将二进制信息解码成对应类型的数据 ;

在这里插入图片描述
在这里插入图片描述

如上图所示 , 如果从 Flutter 端向 Android 端发送 int 类型数据 , 将 Dart 中的 int 类型 转为 Android 端的 Integer 类型 ;

只支持上图中的类型 , 即基本数据类型和集合类型 , 不支持自定义类型 ;

BasicMessageChannel 原型 :

代码语言:javascript
复制
/// A named channel for communicating with platform plugins using asynchronous
/// message passing.
///
/// Messages are encoded into binary before being sent, and binary messages
/// received are decoded into Dart values. The [MessageCodec] used must be
/// compatible with the one used by the platform plugin. This can be achieved
/// by creating a basic message channel counterpart of this channel on the
/// platform side. The Dart type of messages sent and received is [T],
/// but only the values supported by the specified [MessageCodec] can be used.
/// The use of unsupported values should be considered programming errors, and
/// will result in exceptions being thrown. The null message is supported
/// for all codecs.
///
/// The logical identity of the channel is given by its name. Identically named
/// channels will interfere with each other's communication.
///
/// See: <https://flutter.dev/platform-channels/>
class BasicMessageChannel<T> {
}

可回复 : 使用该 BasicMessageChannel 通道发送数据 , 对方收到消息后 , 可以进行回复 ;

持续发送 : BasicMessageChannel 通道可以持续发送数据 ;

常用场景 :

  • 持续遍历 : 在 Android 端遍历数据 , 将遍历信息持续发送给 Flutter 端 ;
  • 耗时操作 : Flutter 需要处理耗时计算 , 将信息传给 Android , Android 处理完后 , 回传给 Flutter 计算结果 ;

二、BasicMessageChannel 在 Dart 端的实现


1、BasicMessageChannel 构造方法

Dart 端 BasicMessageChannel 构造函数原型如下 :

代码语言:javascript
复制
  /// Creates a [BasicMessageChannel] with the specified [name], [codec] and [binaryMessenger].
  ///
  /// The [name] and [codec] arguments cannot be null. The default [ServicesBinding.defaultBinaryMessenger]
  /// instance is used if [binaryMessenger] is null.
  const BasicMessageChannel(this.name, this.codec, { BinaryMessenger? binaryMessenger })
  
  /// The logical channel on which communication happens, not null.
  final String name;

  /// The message codec used by this channel, not null.
  final MessageCodec<T> codec;

下面介绍构造函数的参数 :

String name 参数 : Channel 通道名称 , Native 应用端 与 Flutter 中的 Channel 名称 , 必须一致 ;

MessageCodec<T> codec 参数 : 消息编解码器 , 有

4

中实现类型 ; Native 应用端 与 Flutter 中的消息编解码器也要保持一致 ;

2、使用 BasicMessageChannel 接收 Native 发送的消息

创建好 BasicMessageChannel 消息通道后 , 需要为该 Channel 通道设置一个 MessageHandler 消息处理器 , 调用 BasicMessageChannel 的 setMessageHandler 方法 , 设置该消息处理器 ;

这样在 Flutter 的 Dart 端才能接收到 Android Native 端传递来的消息 ;

BasicMessageChannel 的 setMessageHandler 方法原型 :

代码语言:javascript
复制
  /// Sets a callback for receiving messages from the platform plugins on this
  /// channel. Messages may be null.
  ///
  /// The given callback will replace the currently registered callback for this
  /// channel, if any. To remove the handler, pass null as the `handler`
  /// argument.
  ///
  /// The handler's return value is sent back to the platform plugins as a
  /// message reply. It may be null.
  void setMessageHandler(Future<T> Function(T? message)? handler) {
    if (handler == null) {
      binaryMessenger.setMessageHandler(name, null);
    } else {
      binaryMessenger.setMessageHandler(name, (ByteData? message) async {
        return codec.encodeMessage(await handler(codec.decodeMessage(message)));
      });
    }
  }

传入的参数是 Future<T> handler(T message) , 该参数是用于消息处理的 , 需要配合 BinaryMessenger 进行消息处理 ;

3、使用 BasicMessageChannel 向 Native 发送消息

在 Flutter 端如果想 Native 端发送消息 , 使用 BasicMessageChannel 的 send 方法即可 ;

send 方法原型 :

代码语言:javascript
复制
  /// Sends the specified [message] to the platform plugins on this channel.
  ///
  /// Returns a [Future] which completes to the received response, which may
  /// be null.
  Future<T?> send(T message) async {
    return codec.decodeMessage(await binaryMessenger.send(name, codec.encodeMessage(message)));
  }

send 方法 参数 / 返回值 分析 :

  • T message 参数 : Flutter 端要发送给 Native 端的消息 ;
  • Future<T> 返回值 : Native 端回送给 Flutter 端的消息 ;

该 send 方法接收一个 Future<T> 类型返回值 , 该返回值是异步的 ;

也就是说 Dart 端向 Native 端发送一个消息 , Native 端处理完毕后 , 会回传一个异步消息 ;

4、BasicMessageChannel 使用流程

BasicMessageChannel 使用流程 :

首先 , 导入 Flutter 与 Native 通信 的 Dart 包 ;

代码语言:javascript
复制
import 'package:flutter/services.dart';

然后 , 定义并实现 MethodChannel 对象实例 ;

代码语言:javascript
复制
static const BasicMessageChannel _basicMessageChannel =
  	const BasicMessageChannel('BasicMessageChannel', StringCodec());

最后 , 从 BasicMessageChannel 消息通道接收信息 ;

代码语言:javascript
复制
/// 接收 Native 消息 , 并进行回复
/// 从 BasicMessageChannel 通道获取消息
_basicMessageChannel.setMessageHandler((message) => Future<String>((){
  setState(() {
    showMessage = "BasicMessageChannel : $message";
  });
  return "BasicMessageChannel : $message";
}));

或者 , 通过 BasicMessageChannel 向 Native 发送消息 ;

代码语言:javascript
复制
	/// 向 Native 发送消息
    try {
       String response = await _basicMessageChannel.send(value);
    } on PlatformException catch (e) {
      print(e);
    }

三、相关资源


参考资料 :

重要的专题 :

博客源码下载 :

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-08-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、BasicMessageChannel 简介
  • 二、BasicMessageChannel 在 Dart 端的实现
    • 1、BasicMessageChannel 构造方法
      • 2、使用 BasicMessageChannel 接收 Native 发送的消息
        • 3、使用 BasicMessageChannel 向 Native 发送消息
          • 4、BasicMessageChannel 使用流程
          • 三、相关资源
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档