How to Integrate Web-Sockets with your Server in Flutter

Aman Khan Roohani
2 min readDec 22, 2021

Disclaimer :- This article is for developers who have some prior knowledge of how web-sockets work in practical. If you don’t know what web-sockets are and how they work. Go through this first . Thank you.

Hi there! I’ll tell you an instance where me and my fellow developer were given a simple task i.e to integrate web-sockets in our flutter app. That looked easy as we thought we’ll get the resources easily especially according to our use cases. But that was not the case, when we started researching about web-sockets we found so less amount of articles and resources available at our disposal.

Photo by Fahim Muntashir on Unsplash

Of-course we started with the flutter doc article Working with websockets, as it was the most authentic place to start with. But what we found was there were not much use cases related to it, even on other channels. So we (Me & Gopi) decided to figure it out for ourselves, my fellow developer, still new to Flutter but coming with an Android native background started putting more efforts figuring out how to make it work synchronously.

So what was our problem statement? Our task was to update realtime price values as they transmit from the socket on the app. While the flutter docs state how we could get the values while adding and displaying them ,we wanted in a proper manner so that we can update them with the previous value we got. There was some info gap on how to get it done.

We started figuring out different packages related to sockets and finally found one suitable for the job i.e socket_io_client. The idea was to get all the values of stocks from the socket as they update. And we could access those using keys (specified in Server) and update each individual stock price value using a for loop. For that we decided to use Maps.

For example if your server socket url is https://example.in:3502, then we defined the socket as :-

static IO.Socket socket = IO.io("https://example.in:3502", <String, dynamic>{
'transports': ['websocket'],
});

And used this code to switch on the socket listen:-

if (socket.connected) =>
socket.on(symbols, (data) =>
if (data != null) =>
Map<String, dynamic> socketdata = data;socketdata.keys.forEach((key) =>
if (key == "updated_price") =>
for (int i = 0; i < stocks.length; i++) =>
if (symbols == stocks![i].symbol) {
setState(() {
stocks![i].lastPrice = double.parse(socketdata[k].toString());
});
});
);

Notice that here “=>” means “{}”, “socket” is the const value, “symbols” are stock names. Using this code we were able to display updated values always instantly.

Usage of setState meant that the variable was updating the views as we were getting new values from the server. We used the variable to display the updated data in UI.

--

--

Aman Khan Roohani

Cross Platform Developer (Flutter) | Google Groups Contributor