zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

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

flutter通信开发 实现 混合 native
2023-06-13 09:17:55 时间

文章目录

一、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 方法中设置监听 ;

  @override
  void 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();
  }

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

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

三、相关资源


参考资料 :

重要的专题 :

博客源码下载 :