搜索插件、代码仓与 APP 分类

插件详情v0.3.0

streams_channel

StreamsChannel 受 EventChannel 启发。它允许在 Flutter 和平台端之间创建事件流。

近 30 天下载
169
喜欢数
14
Pub 分数
40

安装插件

flutter pub add streams_channel

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

StreamsChannel 是一个受 EventChannel 启发的 Dart 包,支持 Flutter 与平台端之间的双向流式事件传输。它通过允许 Flutter 从原生平台(如 Android 或 iOS)接收连续数据流,并实现反向通信,从而促进实时通信。该包专为与特定平台代码无缝集成而设计,简化了异步事件流的处理,无需复杂的样板代码。该包轻量且专注于基于流的交互,非常适合用于实时更新、传感器数据或后台通知等场景。

适合场景

  • 实时数据同步
  • 传感器数据流
  • 后台任务通知
  • 实时事件直播
  • 平台到Flutter通信

主要特点

  • 双向流支持
  • 事件通道的简单 API
  • 轻量且依赖极少
  • 原生平台集成
  • 事件驱动架构

适合对象

  • 开发实时功能的开发者
  • 需要平台侧事件处理的应用
  • 使用原生插件的项目
  • 处理异步数据流的团队
  • 带有原生集成的 Flutter 应用

使用建议

  • 需要平台端实现
  • 仅限基于流的通信
  • 无内置错误处理
  • 不适用于单值响应
  • 依赖于双方的正确设置

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

StreamsChannel for Flutter plugin development

pub package

StreamsChannel is inspired from EventChannel. It allows to create streams of events between Flutter and platform side.

Rationale

EventChannel allows to only create a single open stream per channel. On the first subscription, the stream will be open and it's possible to pass arguments from Flutter to platform side. Subsequent subscriptions will either re-use the open stream or override it with a new one.

In order to have multiple streams open at the same time, with different parameters for stream initialization, one has to create multiple EventChannel. And it gets complicated if the number of streams is dynamic.

Installation

Follow the instructions: https://pub.dev/packages/streams_channel#-installing-tab-

How it works

StreamsChannel works in a similar way than EventChannel. The difference is that it supports multiple open streams at the same time.

On the platform side, the channel takes a stream handler factory:

let channel = FlutterStreamsChannel(name: "my_channel", binaryMessenger: plugin.registrar.messenger())
channel.setStreamHandlerFactory { arguments in
  return MyHandler(arguments) // MyHandler is an instance FlutterStreamHandler
}

On the flutter side, each call to receiveBroadcastStream(args) will create a new stream, that won't replace any previous one that is still running.

  1. The first subscription to the stream will create a new stream handler using the factory on the platform side, then trigger onListen on the handler;
  2. The last subscription to the stream will trigger onCancel on the handler, then destroy the handler instance
  3. If a new first subscription happens afterwards, repeat step 1.

Under the hood, StreamsChannel tracks each stream with a simple auto-incremented unique id.

Example

Flutter side
final StreamsChannel channel = new StreamsChannel('some_channel');

// continuous stream of events from platform side, match some args
channel.receiveBroadcastStream('some args')
  .listen((data) {
    // do something
  });

// another continuous stream of events from platform side, matching some other args
channel.receiveBroadcastStream('some other args')
  .listen((data) {
    // do something
  });
Platform side
Android
public class DemoPlugin {
  public static void registerWith(PluginRegistry.Registrar registrar) {
    final StreamsChannel channel = new StreamsChannel(registrar.messenger(), "streams_channel_test");
    channel.setStreamHandlerFactory(new StreamsChannel.StreamHandlerFactory() {
      @Override
      public EventChannel.StreamHandler create(Object arguments) {
        return new StreamHandler();
      }
    });
  }

  // Send "Hello" 10 times, every second, then ends the stream
  public static class StreamHandler implements EventChannel.StreamHandler {

    private final Handler handler = new Handler();
    private final Runnable runnable = new Runnable() {
      @Override
      public void run() {
        if (count > 10) {
            eventSink.endOfStream();
        } else {
            eventSink.success("Hello " + count + "/10");
        }
        count++;
        handler.postDelayed(this, 1000);
      }
    };

    private EventChannel.EventSink eventSink;
    private int count = 1;

    @Override
    public void onListen(Object o, final EventChannel.EventSink eventSink) {
      this.eventSink = eventSink;
      runnable.run();
    }

    @Override
    public void onCancel(Object o) {
      handler.removeCallbacks(runnable);
    }
  }
}
iOS
@interface StreamHandler : NSObject<FlutterStreamHandler>
  @property(strong, nonatomic) NSTimer *timer;
  @property(assign, nonatomic) NSInteger count;
@end

@implementation DemoPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {

  FlutterStreamsChannel *channel = [FlutterStreamsChannel streamsChannelWithName:@"streams_channel_test" binaryMessenger:registrar.messenger];
  [channel setStreamHandlerFactory:^NSObject<FlutterStreamHandler> *(id arguments) {
    return [StreamHandler new];
  }];
}

@end

// Send "Hello" 10 times, every second, then ends the stream
@implementation StreamHandler

- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
  self.count = 1;
  self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
    if(self.count > 10) {
      events(FlutterEndOfEventStream);
    } else {
      events([NSString stringWithFormat:@"Hello %ld/10", (long)self.count]);
      self.count++;
    }
  }];

  return nil;
}

- (FlutterError *)onCancelWithArguments:(id)arguments {
  [self.timer invalidate];
  self.timer = nil;
  return nil;
}
@end

Author

Beacons plugin is developed by Loup, a mobile development studio based in Montreal and Paris.
You can contact us at <hello@loup.app>

License

Apache License 2.0

所属分类

源码仓库

使用此插件的项目