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

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

文章目录

一、BasicMessageChannel 简介

二、BasicMessageChannel 在 Dart 端的实现

1、BasicMessageChannel 构造方法

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

3、使用 BasicMessageChannel 向 Native 发送消息

4、BasicMessageChannel 使用流程






一、BasicMessageChannel 简介


BasicMessageChannel 简介 :


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


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




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


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



BasicMessageChannel 原型 :


/// 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 构造函数原型如下 :


/// 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 44 中实现类型 ; Native 应用端 与 Flutter 中的消息编解码器也要保持一致 ;



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


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


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



BasicMessageChannel 的 setMessageHandler 方法原型 :


/// 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 方法原型 :


/// 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 包 ;


import 'package:flutter/services.dart';


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


static const BasicMessageChannel _basicMessageChannel =
    const BasicMessageChannel('BasicMessageChannel', StringCodec());


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


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


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


/// 向 Native 发送消息
    try {
       String response = await _basicMessageChannel.send(value);
    } on PlatformException catch (e) {
      print(e);
    }




目录
相关文章
|
传感器 Android开发 iOS开发
Flutter插件开发指南02: 事件订阅 EventChannel
上一节我们讲了 Channel 通道,但是如果你是卫星定位业务,原生端主动推消息给 Flutter 这时候就要用到 EventChannel 通道了。 本节会写一个 1~50 的计数器,到 50 后自动关闭原生的消息订阅。
399 1
Flutter插件开发指南02:  事件订阅 EventChannel
|
iOS开发
Flutter与iOS原生通信方式
Flutter与iOS原生通信方式
813 2
|
小程序
Flutter CustomScrollView 效果-顶栏透明与标签栏吸顶
Flutter CustomScrollView 效果-顶栏透明与标签栏吸顶
|
CDN
Cocoapods报错 [!] CDN: trunk URL couldn't be downloaded: 解决方法
Cocoapods报错 [!] CDN: trunk URL couldn't be downloaded: 解决方法
1991 0
|
7月前
|
API Android开发 iOS开发
除了permission_handler插件,还有哪些方法可以实现Flutter动态申请权限?
除了permission_handler插件,还有哪些方法可以实现Flutter动态申请权限?
464 68
|
设计模式 C# C++
责任链模式(Chain of Responsibility Pattern)
责任链模式是一种行为型设计模式,允许多个对象按顺序处理请求,直到某个对象处理为止。适用于多个对象可能处理同一请求的场景,如请假审批流程。优点是灵活性高、降低耦合,但责任链过长可能影响性能。
|
存储 JavaScript 前端开发
在Flutter开发中,状态管理至关重要。随着应用复杂度的提升,有效管理状态成为挑战
在Flutter开发中,状态管理至关重要。随着应用复杂度的提升,有效管理状态成为挑战。本文介绍了几种常用的状态管理框架,如Provider和Redux,分析了它们的基本原理、优缺点及适用场景,并提供了选择框架的建议和使用实例,旨在帮助开发者提高开发效率和应用性能。
270 4
|
XML JSON Kubernetes
什么是 YAML?:一种简洁高效的数据序列化格式
什么是 YAML?:一种简洁高效的数据序列化格式
1961 0
|
开发工具 Android开发
解决Android Studio编译提示NDK is missing a “platforms“ directory
解决Android Studio编译提示NDK is missing a “platforms“ directory
692 1
|
UED
Flutter之ListView实现自动滑动到底部
Flutter之ListView实现自动滑动到底部
594 1

热门文章

最新文章