Orientação gerada a partir de informações públicas. Apenas para referência.
StreamsChannel é um pacote Dart inspirado no EventChannel, permitindo a transmissão bidirecional de eventos entre o Flutter e o lado da plataforma. Facilita a comunicação em tempo real, permitindo que o Flutter receba fluxos contínuos de dados das plataformas nativas (como Android ou iOS) e vice-versa. Projetado para integração perfeita com código específico da plataforma, simplifica o manuseio de fluxos assíncronos de eventos sem exigir boilerplate complexo. O pacote é leve e focado em interações baseadas em streams, sendo ideal para casos de uso envolvendo atualizações em tempo real, dados de sensores ou notificações em segundo plano.
Casos de uso
Sincronização de dados em tempo real
fluxo de dados do sensor
Notificações de tarefas em segundo plano
transmissão ao vivo de eventos
Comunicação entre plataforma e Flutter
Principais recursos
Suporte a fluxo bidirecional
API simples para canais de eventos
Leve e dependências mínimas
Integração com plataforma nativa
Arquitetura orientada a eventos
Indicado para
Desenvolvedores criando recursos em tempo real
Aplicativos que precisam de tratamento de eventos do lado da plataforma
Projetos usando plug-ins nativos
Equipes trabalhando com fluxos de dados assíncronos
Aplicativos Flutter com integrações nativas
Considerações
Requer implementação do lado da plataforma
Limitado à comunicação baseada em fluxo
Sem tratamento de erro embutido
Não adequado para respostas de valor único
Depende de uma configuração adequada em ambos os lados
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
StreamsChannel for Flutter plugin development
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.
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;
The last subscription to the stream will trigger onCancel on the handler, then destroy the handler instance
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
finalStreamsChannel channel = newStreamsChannel('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);
}
}
}