欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

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

发布时间:2025/6/17 编程问答 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 EventChannel 通信 ) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

文章目录

  • 一、EventChannel 简介
  • 二、EventChannel 在 Dart 端的实现
    • 1、EventChannel 构造方法
    • 2、创建广播流 Stream
    • 3、设置监听回调函数
    • 4、EventChannel 使用流程
  • 三、相关资源





一、EventChannel 简介



EventChannel 一般用于持续的通信 , 如 : 将 Android 应用中采集的陀螺仪 , GPS 等信息 , 持续的发送给 Flutter 应用 ;

该通信时单向的 , 收到信息的一方无法回复 ;





二、EventChannel 在 Dart 端的实现




1、EventChannel 构造方法


EventChannel 的构造函数原型如下 :

class EventChannel {/// Creates an [EventChannel] with the specified [name].////// The [codec] used will be [StandardMethodCodec], unless otherwise/// specified.////// Neither [name] nor [codec] may be null. The default [ServicesBinding.defaultBinaryMessenger]/// instance is used if [binaryMessenger] is null.const EventChannel(this.name, [this.codec = const StandardMethodCodec(), BinaryMessenger? binaryMessenger]): assert(name != null),assert(codec != null),_binaryMessenger = binaryMessenger;/// The logical channel on which communication happens, not null.final String name;/// The message codec used by this channel, not null.final MethodCodec codec; }

EventChannel 构造方法参数说明 :

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

  • MethodCodec<T> codec 参数 : 消息编解码器 , 默认类型是 StandardMethodCodec ; Native 应用端 与 Flutter 中的消息编解码器也要保持一致 ;


2、创建广播流 Stream


创建了 EventChannel 实例对象之后 , 调用

/// Sets up a broadcast stream for receiving events on this channel.////// Returns a broadcast [Stream] which emits events to listeners as follows:////// * a decoded data event (possibly null) for each successful event/// received from the platform plugin;/// * an error event containing a [PlatformException] for each error event/// received from the platform plugin.////// Errors occurring during stream activation or deactivation are reported/// through the [FlutterError] facility. Stream activation happens only when/// stream listener count changes from 0 to 1. Stream deactivation happens/// only when stream listener count changes from 1 to 0.Stream<dynamic> receiveBroadcastStream([ dynamic arguments ]) {}

方法 , 可以创建一个 广播流 Stream , 调用该 Stream 实例对象的 listen 方法 , 可以注册消息持续监听 , 用于从 Channel 消息通道中持续接收消息 ; 如果要停止监听 , 可以调用 Stream 的 cancel 方法 ;

receiveBroadcastStream 方法参数 / 返回值 说明 :

  • [ dynamic arguments ] 参数 : 监听 Native 传递来的消息时 , 向 Native 传递的数据 ;
  • Stream<dynamic> 返回值 : 创建的监听用的广播流 ;

注意 : 消息的监听 , 和 取消监听 , 一定个要一一对应 , 防止出现


3、设置监听回调函数


调用 Stream 的 listen 方法 , 传入两个方法参数 ,

StreamSubscription<T> listen(void onData(T event)?,{Function? onError, void onDone()?, bool? cancelOnError});

第一个参数 void onData(T event) , 参数为 T 泛型 , 返回值 void , 这是消息到来后回调的函数 ;

Function? onError 参数 , 参数 和 返回值都是 void , 这是出现错误后回调的函数 ;


代码示例 :

// 注册 EventChannel 监听_streamSubscription = _eventChannel.receiveBroadcastStream()/// StreamSubscription<T> listen(void onData(T event)?,/// {Function? onError, void onDone()?, bool? cancelOnError});.listen(/// EventChannel 接收到 Native 信息后 , 回调的方法(message) {setState(() {/// 接收到消息 , 显示在界面中showMessage = message;});},onError: (error){print(error);});

4、EventChannel 使用流程


使用流程 :

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

import 'package:flutter/services.dart'; import 'dart:async';

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

static const EventChannel _eventChannel =EventChannel('EventChannel');/// 监听 EventChannel 数据的句柄late StreamSubscription _streamSubscription;

接着 , 创建广播流 , 并监听消息 , 一般在 initState 方法中设置监听 ;

@overridevoid initState() {// 注册 EventChannel 监听_streamSubscription = _eventChannel.receiveBroadcastStream()/// StreamSubscription<T> listen(void onData(T event)?,/// {Function? onError, void onDone()?, bool? cancelOnError});.listen(/// EventChannel 接收到 Native 信息后 , 回调的方法(message) {setState(() {/// 接收到消息 , 显示在界面中showMessage = message;});},onError: (error){print(error);});super.initState();}

最后 , 如果监听完毕 , 取消监听 ; 这样可以防止不必要的内存泄漏 ;

@overridevoid dispose() {// 取消监听_streamSubscription.cancel();super.dispose();}



三、相关资源



参考资料 :

  • Flutter 官网 : https://flutter.dev/
  • Flutter 插件下载地址 : https://pub.dev/packages
  • Flutter 开发文档 : https://flutter.cn/docs ( 强烈推荐 )
  • 官方 GitHub 地址 : https://github.com/flutter
  • Flutter 中文社区 : https://flutter.cn/
  • Flutter 实用教程 : https://flutter.cn/docs/cookbook
  • Flutter CodeLab : https://codelabs.flutter-io.cn/
  • Dart 中文文档 : https://dart.cn/
  • Dart 开发者官网 : https://api.dart.dev/
  • Flutter 中文网 : https://flutterchina.club/ , http://flutter.axuer.com/docs/
  • Flutter 相关问题 : https://flutterchina.club/faq/ ( 入门阶段推荐看一遍 )
  • GitHub 上的 Flutter 开源示例 : https://download.csdn.net/download/han1202012/15989510
  • Flutter 实战电子书 : https://book.flutterchina.club/chapter1/
  • Dart 语言练习网站 : https://dartpad.dartlang.org/

重要的专题 :

  • Flutter 动画参考文档 : https://flutterchina.club/animations/

博客源码下载 :

  • GitHub 地址 : ( 随博客进度一直更新 , 有可能没有本博客的源码 )

    • Flutter Module 工程 : https://github.com/han1202012/flutter_module
    • Android 应用 : https://github.com/han1202012/flutter_native
    • 注意 : 上面两个工程要放在同一个目录中 , 否则编译不通过 ;
  • 博客源码快照 : https://download.csdn.net/download/han1202012/21670919 ( 本篇博客的源码快照 , 可以找到本博客的源码 )

总结

以上是生活随笔为你收集整理的【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 在 Flutter 端实现 EventChannel 通信 )的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。