How to implement socket in flutter

First, you need to know what socket is!


Well, the socket is an application that creates communication between front-end and back-end software. Thus, whenever an object change occurs in the backend's return, an event is generated to update the frontend.

Great, now let's get to the code!

You need to import the flutter_pusher package into your project.

Download in: https://pub.dev/packages/flutter_pusher

...

Your backend should return config socket. Example:

"data": {

"driver": "######",

"key": "######",

"secret": "######",

"app_id": "######",

"options": {

"cluster": "######",

"useTLS": ######

},

"channel_name": "######"

},

About the properties, look the package documentation.

With this, you can to conect your pusher to listen future changes.

pusherKey = response.data.key;

pusherSecret = response.data.secret;

pusherAppID = response.data.app_id;

pusherCluster = response.data.options.cluster;

pusherUseTLS = response.data.options.useTLS;


await pusher.connect();


Nice, now you can create a method to get a information after change.

This method has called by the aplication whenever has change at object, automacally.

Look example code bellow.


pusher.onMessage.listen((data) async {

switch (data.eventName) {

//Here you manage the aplication according the event

}

print(data.body);

//Look above the body property, is possible too get the object and manage anyway

}, onDone: () {

print('Done listening to pusher');

}, onError: (error) {

print('Error listening to pusher');

});


Contact me to more informations.