Using Pusher in Flutter

Mirkan
Mirkan
Aug 10 · 3 min read
Photo: Neven Krcmarak

What’s Pusher?

Pusher is a hosted service for providing real-time data and functionality to your mobile and web apps easily.

The project that I now working is using Pusher, and while searching for what’s Pusher, I’ve came across a Flutter package. The package is working fine and I’m glad I find it so quick. Thanks to Flutter community and HomeXlabs.

Pusher Websocket Package

This package wraps pusher-websocket-java and pusher-websocket-swift plugins, it’s good to know that it’s unofficial and not maintained by Pusher.

After creating your Pusher account, you need to get key and cluster info for your project. After that, add pusher_websocket_flutter to your pubsec.yaml.

pusher_websocket_flutter

Let’s create a file called pusher_service.dart. We will initialize and connect Pusher here, after that we’ll subscribe to a channel and bind events to this channel to listen data.

Channels and Events

Channels and events are Pusher specific terms, don’t confuse them with PlatformChannels. Channels are kind of namespaces to filter and group events. We can define events like something happen in your system or a notification. For example, we can have public channel and message-create event.

I have last event, last connection state and channel in my PusherService class.

Now write init, connect, subscribe and unsubcribe methods. In init method, give your key ve cluster. Init method sets up the Pusher, that’s why we need to key and cluster. After that, connect with your connect method, and subscribe to a channel with your subscribe method.

Now we will listen events from this channel. I’m thinking of adding the incoming data to the StreamController and then use StreamBuilder to build my widget whenever new data arrives.

Under the lastEvent, lastConnectionState and channel, I’m defining this:

In the bindEvent method below, I’m adding every data in the incoming events to a sink named _inEventData. In my unBindEvent method, I’m simply unbind the channel and close this StreamController.

Here’s a method to call the previous methods one by one.

Now I can show the data in my homescreen with StreamBuilder. In the initState method of the widget, I’m calling firePusher method. In StreamBuilder, if there’s no data, I’m displaying the CircularProgressIndicator, if there’s a data, I’m using Text widget to show it. Lastly, in the dispose method, I call unbindEvent method.

In the event creator on Pusher.com(in Debug Console tab), I’m sending events to test.

Questions are always welcome on Twitter @mirkancal and LinkedIn. Keep
Flutterin’.

Checkout my other article:
Using SVG in Flutter

Flutter Community

Articles and Stories from the Flutter Community

Mirkan

Written by

Mirkan

İzmir’den Flutter mühendisiyim. Stackoverflow’da Flutter sorularını cevaplamayı seviyorum.

Flutter Community

Articles and Stories from the Flutter Community