Pusher in Flutter: A beginner’s guide

Talha
7 min readDec 29, 2023

--

Pusher is a real-time communication service that provides instant updates between client or several clients and server. Pusher use the power of Websockets and provide a comprehensive framework of channels and events to provide real-time updates across multiple clients. Pusher is widely used for its simplicity of providing events rather than building your own separate Socket IO server, that’s why its pretty popular to be used with frontend mobile technologies like Flutter, React Native, Native android and iOS.

In this tutorial we shall be using pusher_channels_flutter package to implement pusher in our Flutter app and listen to various events emitted by the server side of pusher. First of all, we need to add this package in our pubspec.yaml file under dependencies,

Next, for our own easiness we shall make a singlton class (a class with private constructor), the purpose of singlton class is that we can easilty access the methods and public variables using the class name. In our singlton class make sure to get the instance of PusherChannelsFlutter variable, this is also a singleton class. For now ignore the PusherAuthRepo variable.

Now we can use this pusher variable to connect initialise pusher and subscribe to channel and listen and send events.

To initialise pusher we need to call the pusher.init method and need to pass three arguments, a pusher key, a pusher cluster and an authoriser function. The “Pusher key” refers to the API key associated with your Pusher account. It uniquely identifies your application and is used to authenticate and connect your application with the Pusher service. The “Pusher cluster” refers to the geographical region where Pusher’s servers are located. If you already have pusher set up on your server side, you shoud have both of these.

For now you can ignore onPrivatePostChannel and onPrivateCommentChannel function calls and the token (which is our user token), its something used to authenticate our pusher connection.

The onAuthorizer function sends a post request to pusher server to verify our pusher connection. The pusher in this regard gives us three parameters (channelName, socketId and options) which we send along with the request to verify the connection. In our case we configured the pusher service to accept the user auth token too verify a certain user, that’s why we were using the token in the first place.

The PusherAuthRepo variable which we defined earlier referred to this API repo class. You can ignore the BaseRepo.handleApiErrors its something i used to handle the API errors but you can wrap your request in simple try catch block and it’ll work fine.

When we’ll call the pusher.initialise this code will be run in onAuthorizer function to validate our connection. Once our connection gets validated, we can start listen to events and and send events as well. For caution, except the use of token, make sure authorizer function in PusherAuthRepo has the same kind of headers and body, this is important otherwise you might get some error from pusher, also make sure to send a post request as shown in the image above.

Now its time to define our channels and events in our PusherServices class, for the sake of simplicity i stored the name in the individual variables as show below,

Hence, here i have defined my channels and events which i needed, the connected and disconnected are two special kind of events provided by pusher directly upon connection and disconnection, To disconnect from the pusher we simple can call disconnectPuhser function as below,

So this function will disconnect and unsubscribe all the channels if pusher is connected already, pusher.connectionState return either “CONNECTED” or “DISCONNECTED” as we have defined earlier, and pusher.unsubscribe function takes channel name as argument and unsubscribe from that channel. To make connect and disconnect pusher more effectively i wrote another function called reinitializePusher which first disconnects the pusher and then reconnects it to avoid any mistakes during runtime, this is useful once user logout and login with another account, we need to authenticate puhser for second account, so we disconnect pusher for first account if its running and reconnect it again.

Now its time to subscribe to our channels, if you remember, in our initializePusher function we ignored two function calls earlier,

onPrivatePostChannel is used to connect private-postChannel and onPrivateCommentChannel is used to connect to private-commentChannel.

To subscribe to a channel, we call pusher.subscribe and it takes 2 arguments, the channel name and a callback function to listen events. You also need to call pusher.connect after subscribing to a channel. Anytime an event is emitted the callback function provides the update through an event as shown below,

Now we can use this event to provide real-time change in our app, to provide specific operations, the event is passed to another method so that it can be utilised more effectively. Since both function has same kind of logic, so let’s keep our focus on onPrivatePostChannel function,

onPrivatePostChannelEvent function takes the event from onPrivatePostChannel function and check the event name and perform the respective operation.

Now if we print the event we find that data is in the form of text which needs to be decoded into Map or dictionary (JOSN format) before we can use it, so we use json.decode to parse the event data and extract the useful information from it.

Here’s a representation of the event we received from the pusher

As we discussed earlier, we need to parse the event data so form that purpose we can use jsonDecode function from dart:convert library, after decoding the event data we get a Map or Dictionary and we can extract the data sent in the event from it, this data we get from the event now can be used to provide real time change in the app.

Below shown a brief example, that how we can parse the event and get the real-time data form it,

Since my event included a list of US states so upon parsing i get the list of states, make sure to wrap your parsing in a try catch block to avoid the errors, once you get your data from the event it can be used in the app.

To send an event to pusher server, we can use pusher.trigger function and pass the PusherEvent class with channelName, eventName and data (can be textual). This is useful when one client want to provide the change to another client, for example, adding items in a shopping cart, the client buying item can send event to store client that following items have been added.

Now we have learned how to initialise pusher and how to subscribe to channel and how to send, receive and parse the pushser events, but one thing which still needs to be done is where in the app you want to call the PusherSerives.reinitializePusher function.

Its more really a personal preference, in my case i called it in the bottom naviagtion bar class, as soon as Flutter renders this, the pusher get initialised and start listening to events.

Here’s i called in the initState function, but i also have called PusherSerives.reinitializePusher in my login and signup function, the reason is that, if your app has guest mode and you don’t allow pusher in guest mode but user can login and signup to your app from inside the app rather than from start, you need to initialise pusher in login and signup functions in that case but its more like a personal preference that where do you want to start listening to your pusher events.

So, here was a brief introduction of how to use pusher in our Flutter app, in this article we covered the how we can setup pusher, how to initialise and authorise our pusher connection, and then we dived into details of connecting and subscribing to pusher channels and listening to events, along with how to parse and use data sent in events. Along the way, we also learned, how we can send our own custom events from our Flutter app and then we talked about where’s optimally you should initialise pusher in your Flutter app. I tried to simplify this article as much as i could with brief and easy code examples. I hope you learned how you can use pusher in your own Flutter app.

As you embark on your journey with Pusher, remember that innovation knows no bounds. Explore, experiment, and let your creativity shape the real-time experiences you bring to life in your Flutter projects. Happy coding, and may your apps always stay in sync with the heartbeat of your users!

--

--