Flutter与原生通信之EventChannel

EventChannel 是原生向Flutter传递数据流的通道,属于单向传输,只能由原生端调用,Flutter端是接收信息,常见的有网络变化监听,屏幕横竖屏切换,位置切换,电池电量,远程通知等事件。

下面结合iOS端代码来描述下使用方法

Flutter端代码

final eventChannel = const EventChannel('test_event_channel');

定义channel

Future<void> setEventChannel() async {
  _streamSubscription = eventChannel.receiveBroadcastStream().listen((event) {
    print('Flutter收到了原生端的事件:$event');
  }, onError: (error) {
    print(error);
  }, onDone: () {
    print('done');
  }, cancelOnError: true);
}

组件初始化中设置回调

  • 闭包第一个回调为onData,参数event为泛型,表示原生端返回的信息内容
  • onError: 报错会执行
/// Otherwise it is called with just the error object.
/// If [onError] is omitted, any errors on this stream are considered unhandled,
/// and will be passed to the current [Zone]'s error handler.
/// By default unhandled async errors are treated
/// as if they were uncaught top-level errors.
  • onDone: 时间完成会执行
/// If this stream closes and sends a done event, the [onDone] handler is
/// called. If [onDone] is `null`, nothing happens.
  • cancelOnError: 报错后是否取消事件
/// If [cancelOnError] is `true`, the subscription is automatically canceled
/// when the first error event is delivered. The default is `false`.

iOS原生端

class EventChannelManager: NSObject  {
    var channel: FlutterEventChannel
    var eventSink: FlutterEventSink?
    var count = 0
    var timer: Timer?
    init(messager: FlutterBinaryMessenger) {
        channel = FlutterEventChannel(name: "test_event_channel", binaryMessenger: messager)
    }
    func config() {
        channel.setStreamHandler(**self**)
    }
    func startTimer() {
       timer = Timer(timeInterval: TimeInterval(2), target: self, selector: #selectortriggerEventChannel), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .common)
    }
    @objc func triggerEventChannel() {
        count += 1
        eventSink?("当前数值为:\(count)")
    }
}

extension EventChannelManager : FlutterStreamHandler {

    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events
        startTimer()
        return nil
    }
    func onCancel(withArguments arguments: **Any**?) -> FlutterError? {
        return nil
    }
}

AppDelegate中调用:

let eventChannelManager = EventChannelManager(messager: messager)
eventChannelManager.config()

和其他两种通信方式不同的是,EventChannel需要在原生端实现 FlutterStreamHandler协议,获取到 FlutterEventSink,用它来进行消息的发送

eventSink?("当前数值为:\(count)")

打印结果如下:

截屏2023-08-17 14.24.10.png

全部评论

相关推荐

一个菜鸡罢了:哥们,感觉你的简历还是有点问题的,我提几点建议,看看能不能提供一点帮助 1. ”新余学院“别加粗,课程不清楚是否有必要写,感觉版面不如拿来写一下做过的事情,教育经历是你的弱势就尽量少写 2. “干部及社团经历”和“自我评价”删掉 3. 论文后面的“录用”和“小修”啥的都删掉,默认全录用,问了再说,反正小修毕业前肯定能发出来 4. 工作经验和研究成果没有体现你的个人贡献,着重包装一下个人贡献
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务