Orientação gerada a partir de informações públicas. Apenas para referência.
O plugin Pusher Channels para Flutter permite comunicação em tempo real em aplicativos Flutter ao se conectar ao Pusher Channels, um serviço para streaming de dados ao vivo. Ele permite que os aplicativos recebam atualizações instantâneas por meio de canais e eventos, ideal para funcionalidades como bate-papo, notificações, placares ao vivo e ferramentas colaborativas. O plugin suporta tanto as plataformas Android quanto iOS e se integra perfeitamente à arquitetura reativa do Flutter. Com APIs simples baseadas em eventos, os desenvolvedores podem se inscrever em canais, ouvir eventos e gerenciar dados de presença. Foi projetado para interações em tempo real com baixa latência e escalabilidade.
Casos de uso
Aplicações de bate-papo em tempo real
Placar ao vivo e atualizações esportivas
Ferramentas de edição colaborativa
Sistemas de notificação instantânea
indicadores de presença do usuário
Principais recursos
Transmissão em tempo real de eventos
Suporte a canal e canal privado
Gerenciamento de presença e assinatura
Compatibilidade multiplataforma (iOS e Android)
API simples baseada em eventos
Indicado para
Desenvolvedores criando aplicativos interativos ao vivo
Equipes que precisam de sincronização em tempo real dos dados
Aplicativos que exigem notificações instantâneas do usuário
Projetos usando serviços de backend do Pusher
Aplicativos Flutter com atualizações de conteúdo dinâmico
Considerações
Requer uma conta Pusher e credenciais do aplicativo
Limitado ao backend do Pusher Channels
Pode exigir configuração adicional para autenticação
Depende da conectividade de rede para atualizações em tempo real
Não adequado para aplicativos de primeira linha offline
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
To integrate the plugin in your Flutter App, you need
to add the plugin to your pubspec.yaml:
dependencies:pusher_channels_flutter:'^1.0.1'
iOS specific installation
The Pusher Channels Flutter plugin adds the
pusher-websocket-swift cocoapod to your project.
You probably need to run a
$ pod install
in the ios directory.
Android specific installation
Gradle should automatically include the
pusher-websocket-java dependency.
Web specific installation
For web this plugin uses pusher-js, you can load it from the Pusher CDN, or add it locally. You
probably want to include it in the head of your
index.html page:
The PusherChannelFlutter class is a singleton, that
can be instantiated with getInstance(). Then you need to initialize the client with a number of configuration options, here is a quick example with a number of callbacks options:
After calling init(...) you can connect to the Pusher servers.
You can subscribe to channels before calling connect()
Configuration
There are a number of configuration parameters which can be set for the Pusher client. The following table
describes for which platform the parameter is available:
parameter
Android
iOS
Web
activityTimeout
✅
✅
✅
apiKey
✅
✅
✅
authParam
⬜️
⬜️
✅
authEndpoint
✅
✅
✅
authTransport
⬜️
⬜️
✅
cluster
✅
✅
✅
disabledTransports
⬜️
⬜️
✅
enabledTransports
⬜️
⬜️
✅
enableStats
⬜️
⬜️
✅
ignoreNullOrigin
⬜️
⬜️
✅
logToConsole
⬜️
⬜️
✅
maxReconnectGapInSeconds
✅
✅
⬜️
maxReconnectionAttempts
✅
✅
⬜️
pongTimeout
✅
✅
✅
proxy
✅
⬜️
⬜️
useTLS
✅
✅
⬜️
activityTimeout (double)
After this time (in seconds) without any messages received from the server, a ping message will be sent to check if the connection is still working; the default value is supplied by the server, low values will result in unnecessary traffic.
Allows passing additional data to authorizers. Supports query string params and headers (AJAX only). For example, following will pass foo=bar via the query string and baz: boo via headers:
Additional parameters to be sent when the channel authentication endpoint is called. When using ajax authentication the parameters are passed as additional POST parameters. When using jsonp authentication the parameters are passed as GET parameters. This can be useful with web application frameworks that guard against CSRF (Cross-site request forgery).
CSRF
If you require a CSRF header for incoming requests to the private channel authentication endpoint on your server, you should add a CSRF token to the auth hash under headers. This is applicable to frameworks which apply CSRF protection by default.
The authEndpoint provides a URL that the
Pusher client will call to authorize users
for a presence channel. On how to implement
an authorization service please check here:
use this if you want to be informed of when a channel has successfully been subscribed to, which is useful if you want to perform actions that are only relevant after a subscription has succeeded. For example querying the members for presence channel.
use this if you want to be informed of a failed subscription attempt, which you could use, for example, to then attempt another subscription or make a call to a service you use to track errors.
Called when a member is removed to the presence channel.
onAuthorizer
When passing the onAuthorizer() callback to the init() method, this callback is called to request auth information. For more information on how
to generate the correct information, please look here:
https://pusher.com/docs/channels/library_auth_reference/auth-signatures/
use this if you want to be informed of errors received from Pusher Channels e.g. Application is over connection quota. You can find some of the possible errors listed here.
Connection handling
Connecting
To connect to the Pusher network, just call the connect() method.
await pusher.connect();
Disconnecting
To disconnect to the Pusher network, just call the disconnect() method.
await pusher.disconnect();
Reconnection
There are three main ways in which a disconnection can occur:
The client explicitly calls disconnect and a close frame is sent over the websocket connection
The client experiences some form of network degradation which leads to a heartbeat (ping/pong) message being missed and thus the client disconnects
The Pusher server closes the websocket connection; typically this will only occur during a restart of the Pusher socket servers and an almost immediate reconnection should occur
In the case of the first type of disconnection the library will (as you'd hope) not attempt a reconnection.
Subscribing
Public channels
The default method for subscribing to a channel involves invoking the subscribe method of your client object:
final myChannel = await pusher.subscribe(channelName: "my-channel");
Private channels
Private channels are created in exactly the same way as public channels, except that they reside in the 'private-' namespace. This means prefixing the channel name:
final myPrivateChannel = await pusher.subscribe(channelName: "private-my-channel")
Subscribing to private channels involves the client being authenticated. See the Configuration section for the authenticated channel example for more information.
Private encrypted channels
Similar to Private channels, you can also subscribe to a private encrypted channel. This library now fully supports end-to-end encryption. This means that only you and your connected clients will be able to read your messages. Pusher cannot decrypt them.
The shared secret used to decrypt events is loaded from the same auth endpoint request that is used to authorize your subscription. There is also a mechanism for reloading the shared secret if your encryption master key changes. If an event is encountered that cannot be decrypted, a request is made to your auth endpoint to attempt to load the new shared secret. If that request fails or if the returned secret still cannot decrypt the event then that event will be skipped, the onDecryptionFailure callback function will be called, and the next received event will be processed.
Limitations
Client events are not supported on encrypted channels
final privateEncryptedChannel = await pusher.subscribe(channelName: "private-encrypted-my-channel")
There is also an optional callback in the connection delegate when you can listen for
any failed decryption events:
Presence channels are channels whose names are prefixed by presence-.
The resulting channel object has a member: members that contains the active members of the channel.
final myPresenceChannel = await pusher.subscribe(channelName: "presence-my-channel")
You can also provide functions that will be called when members are either added to or removed from the channel. These are available as parameters to init() globally, or to subscribe() per channel.
Note: The members property of PusherChannel objects will only be set once subscription to the channel has succeeded.
The easiest way to find out when a channel has been successfully subscribed to is to bind to the callback named onSubscriptionSucceeded on the channel you're interested in. It would look something like this:
final pusher = PusherChannelsFlutter.getInstance();
final channels = {};
await pusher.init(
apiKey: API_KEY,
cluster: API_CLUSTER,
authEndPoint: "https://your-server.com/pusher/auth"
);
final myChannel = await pusher.subscribe(
channelName:'presence-my-channel',
onSubscriptionSucceeded: (channelName, data) {
print("Subscribed to $channelName");
print("I can now access me: ${myChannel.me}")
print("And here are the channel members: ${myChannel.members}")
},
onMemberAdded: (member) {
print("Member added: $member");
},
onMemberRemoved: (member) {
print("Member removed: $member");
},
onEvent: (event) {
print("Event received: $event");
},
);
Note that both private and presence channels require the user to be authenticated in order to subscribe to the channel. This authentication can either happen inside the library, if you configured your Pusher object with your app's secret, or an authentication request is made to an authentication endpoint that you provide, again when initializing your Pusher object.
We recommend that you use an authentication endpoint over including your app's secret in your app in the vast majority of use cases. If you are completely certain that there's no risk to you including your app's secret in your app, for example if your app is just for internal use at your company, then it can make things easier than setting up an authentication endpoint.
Unsubscribing
To unsubscribe from a channel, call the unsubscribe() method:
await pusher.unsubscribe("my-channel");
Binding to events
Events can be bound to at 2 levels; globally and per channel. There is an example of this below.
Per-channel events
These are bound to a specific channel, and mean that you can reuse event names in different parts of your client application.
classPusherEvent{
String channelName; // Name of the channel.String eventName; // Name of the event.dynamic data; // Data, usually JSON string. See [parsing event data](#parsing-event-data).String? userId; // UserId of the sending event, only for client events on presence channels.
}
Parsing event data
The data property of PusherEvent contains the string representation of the data that you passed when you triggered the event. If you passed an object then that object will have been serialized to JSON. You can parse that JSON as appropriate.
Receiving errors
Errors received from Pusher Channels can be accessed via the onError callback.
Once a private or presence subscription has been authorized (see authenticating users) and the subscription has succeeded, it is possible to trigger events on those channels. You can do this per channel, or
on the global PusherChannelsFlutter instance.
Events triggered by clients are called client events. Because they are being triggered from a client which may not be trusted there are a number of enforced rules when using them. Some of these rules include:
Event names must have a client- prefix
Rate limits
You can only trigger an event when the subscription has succeeded