Flutter: Integrating Socket IO Client

Hussain Habibullah
Flutter Community
Published in
3 min readJul 12, 2022

What is Web Socket & Socket IO?

Web socket is a two-way, full duplex communication technology, in which the transmission of data is real-time and bi-directional. While Socket.io is a popular library used to implement web sockets.

In this article, we will see how to integrate socket requests in Flutter. The server side can be built on NodeJS, while this article only focuses on the client-side integration in Flutter.

Before that, let us cover some basics and understand how socket requests work. You can skip this part if you are already aware of it.

How does it work?

Our flutter app will be considered as a Client, while your backend is considered as Server and we will be establishing a bi-directional and real-time data transmission between them using Socket IO. Below are the flow steps you need to follow for successful data transmission.

  1. First, we have to build a connection with the server.
  2. Your app will be listening to events, so if a new event arrives, your UI will reflect it immediately (Like listening to new messages in Chat).
  3. You can emit events, maybe when you want to broadcast some data to your backend (Like emitting a new message to Chat).
  4. Don’t forget to close the connection between client and server.

Sounds easy? Let’s see how we can implement it in code!

How to Code?

For the sake of simplicity let’s say we are integrating Chat Socket requests to our flutter app to achieve real-time chat functionality.

Add socket_io_client package in your pubspec.yaml as a dependency:

dependencies:
socket_io_client: ^1.0.2

Import the library,

import 'package:socket_io_client/socket_io_client.dart' as IO;

Establish the connection to the socket server as soon as the user opens Chat Page,

IO.Socket socket;@override
void initState() {
initSocket();
super.initState();
}
initSocket() {
socket = IO.io(APIConstants.socketServerURL, <String, dynamic>{
'autoConnect': false,
'transports': ['websocket'],
});
socket.connect();
socket.onConnect((_) {
print('Connection established');
});
socket.onDisconnect((_) => print('Connection Disconnection'));
socket.onConnectError((err) => print(err));
socket.onError((err) => print(err));
}

When the connection is established, the onConnect callback will be triggered and you can add your logic there, let’s say you want to get all messages or maybe listen for new messages, you can do that all here.

To add a listener, you can use socket.on(), and it will start listening to new events and will be triggered on all emits that happen on the socket server.

socket.on('getMessageEvent', (newMessage) {
messageList.add(MessageModel.fromJson(data));
});

To emit an event, you can use socket.emit(), like this (The map may be different in your case):

sendMessage() {
String message = textEditingController.text.trim();
if (message.isEmpty) return;
Map messageMap = {
'message': message,
'senderId': userId,
'receiverId': receiverId,
'time': DateTime.now().millisecondsSinceEpoch,
};
socket.emit('sendNewMessage', messageMap);
}

Don’t forget to dispose of the connection,

@override
void dispose() {
socket.disconnect();
socket.dispose();
super.dispose();
}

If the socket connection is failing, then you might have to add the following property to your AndroidManifest.xml file application tag:

<application
.....
android:usesCleartextTraffic="true">

If it still fails, then it might be a compatibility issue with your backend socket IO server, check the version info and make sure your server and client library versions are compatible:

Well, that’s how to integrate socket IO requests in a flutter. The package made it all easy.

Thank you for reading, give it a clap if you liked it.

I am open to freelance, full-time, or part-time roles, feel free to reach out at Linkedin, thank you!

--

--