WebSockets in Flutter

What is a WebSockets?

WebSockets are one of the easiest way for two-way communication with a server. It was made because of the limitations that HTTP possessed. Usually in HTTP a client requests data and the server responds to the request. It is a strictly one-way communication whereas WebSockets allow for sending message-based data, similar to UDP, but with the reliability of TCP. WebSocket uses HTTP as the initial transport mechanism, but keeps the TCP connection alive after the HTTP response is received so that it can be used for sending messages between client and server.

Initializing a WebSocket

Update the pubsec.yaml file

sdk: flutter
web_socket_channel: ^1.1.0
WebSocket Class

The above code contains a class that initializes the WebSocket and gets data from it. I have used Getx state management to change the data continuously after every time the data received has changed from the previous instance. I will talk about Getx in the next article.

The _setData function in channel!.stream.listen is used to parse the data received based on the models made for the JSON. The function has not been showcased in this article.

The retryLimit is used to retry to connect to the WebSocket for a certain number of times if it is not connecting on the first try.

Don’t forget to dispose of the WebSocket after using it as it will continue to send data if not disposed.

Implementing WebSocket in a Statefull widget

Add the following snippet in the void function in main.dart if you are also using Getx. WebSocket is the class name of the above snippet,so replace it with your class name.


In the Statefull Widget you are using the WebSocket add the following:

@overridevoid dispose() {    super.dispose();    Get.find<Meal>().closeFoodStream();} //dispose stream@overridevoid initState() {    super.initState();    Get.find<WebSocket>().startStream();} //start stream

It basically starts the websocket stream as soon as the widget satrts to build and the widget is disposed the the stream link is also disposed.

You can then initialize a controller for the Websocket and use it to access the data

final dataController = Get.find<WebSocket>();
//Write Use of Websocket Data
// dataController.data is the data we are getting from the
// WebSOcket

For queries comment down, I would try to clarify them with my utmost strength.

A frustrated engineer trying to find his place.