【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);
    }




目录
相关文章
|
6天前
|
开发框架 Dart 前端开发
【Flutter前端技术开发专栏】Flutter与React Native的对比与选择
【4月更文挑战第30天】对比 Flutter(Dart,强类型,Google支持,快速热重载,高性能渲染)与 React Native(JavaScript,庞大生态,热重载,依赖原生渲染),文章讨论了开发语言、生态系统、性能、开发体验、学习曲线、社区支持及项目选择因素。两者各有优势,选择取决于项目需求、团队技能和长期维护考虑。参考文献包括官方文档和性能比较文章。
【Flutter前端技术开发专栏】Flutter与React Native的对比与选择
|
4月前
|
前端开发 JavaScript Android开发
跨端技术栈综合考察:深入剖析 UniApp、Flutter、Taro 和 React Native 的优势与限制
跨端技术栈综合考察:深入剖析 UniApp、Flutter、Taro 和 React Native 的优势与限制
|
6天前
|
开发框架 前端开发 Android开发
【Flutter 前端技术开发专栏】Flutter 与原生模块通信机制
【4月更文挑战第30天】本文探讨了Flutter作为跨平台开发框架与原生Android和iOS交互的必要性,主要通过方法调用和事件传递实现。文中详细介绍了Flutter与Android/iOS的通信方式,数据传输(包括基本和复杂类型),性能优化,错误处理以及实际应用案例。理解并掌握这一通信机制对开发高质量移动应用至关重要,未来有望随着技术发展得到进一步优化。
【Flutter 前端技术开发专栏】Flutter 与原生模块通信机制
|
9天前
|
开发框架 前端开发 JavaScript
【专栏】Flutter vs React Native:跨平台移动应用开发的比较
【4月更文挑战第27天】本文对比分析了Flutter和React Native两大跨平台移动开发框架。Flutter,由Google推出,以其接近原生的性能、快速启动和流畅滚动受青睐,适合高性能和高度定制的项目。React Native,Facebook维护,依赖JavaScript,虽性能受限,但热重载优势和丰富第三方库使其适合快速迭代的项目。两者都在拓展多平台应用,Flutter在桌面和Web,React Native在Windows。选择框架需考虑项目需求、团队技能和性能效率平衡。
|
13天前
|
Dart 前端开发 JavaScript
《跨平台移动应用开发探索:Flutter vs React Native》
在移动应用开发领域,跨平台技术日益成熟,Flutter和React Native作为两大主流框架备受关注。本文将对比Flutter和React Native在性能、开发体验、生态系统等方面的优劣,并探讨它们在不同场景下的适用性,以帮助开发者选择最适合自己项目的技术方案。
|
4月前
|
移动开发 前端开发 JavaScript
探究移动端混合开发技术:React Native、Weex、Flutter的比较与选择
移动端混合开发技术在移动应用开发领域日益流行,为开发者提供了更高效的跨平台开发方案。本文将比较三种主流混合开发技术:React Native、Weex和Flutter,从性能、生态系统和开发体验等方面进行评估,以帮助开发者在选择适合自己项目的技术时做出明智的决策。
|
4月前
|
移动开发 前端开发 weex
React Native、Weex、Flutter 混合开发技术的比较与选择
移动应用已经成为人们日常生活中不可或缺的一部分,而混合开发技术也随之崛起并逐渐成为主流。本文将比较 React Native、Weex 和 Flutter 三种混合开发技术,并探讨它们各自的优缺点,以及如何根据项目需求做出选择。
59 1
|
前端开发 容器
Flutter的AnimatedDefaultTextStyle实现文本样式的动画过渡切换效果
AnimatedDefaultTextStyle通过动画过渡的方式来切换文本的显示样式
Flutter的AnimatedDefaultTextStyle实现文本样式的动画过渡切换效果
|
4月前
|
监控 Dart 安全
创建一个Dart应用,监控局域网上网记录的软件:Flutter框架的应用
在当今数字时代,网络安全变得愈发重要。为了监控局域网上的上网记录,我们可以借助Flutter框架创建一个强大的Dart应用。在这篇文章中,我们将深入讨论如何使用Flutter框架开发这样一个监控局域网上网记录的软件,并提供一些实用的代码示例。
280 1
|
6天前
|
Dart 前端开发 开发者
【Flutter前端技术开发专栏】Flutter Dart语言基础语法解析
【4月更文挑战第30天】Dart是Google为Flutter框架打造的高效编程语言,具有易学性、接口、混入、抽象类等特性。本文概述了Dart的基础语法,包括静态类型(如int、String)、控制流程(条件、循环)、函数、面向对象(类与对象)和异常处理。此外,还介绍了库导入与模块使用,帮助开发者快速入门Flutter开发。通过学习Dart,开发者能创建高性能的应用。
【Flutter前端技术开发专栏】Flutter Dart语言基础语法解析