websocket flutter

Estimated reading time: 8 minute(s)

In this series, we will be looking at how to implement websockets in Flutter. Before I continue, WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.

This tutorial will span across more than one post so be sure to tune in for updates on it. This first post will be centered on developing the flutter application and I will assume that the reader has some little idea and experience on Flutter Dart.

The end product of this particular tutorial will look like the screenshot below. You can do more to improve the UI design:

This is just an application to simulate a home automation system i.e. controlling applicances remotely but in our case, we will be using websockets instead of the conventional http protocol. So to create a new flutter project, navigate to the folder of your choice and run this command:

flutter create <project-name>

You can use any name for your project. navigate to the lib folder and edit the main.dart file inside it. Don’t worry, the source code will be made available. I will just highlight the important parts you have to look out for.

We can now run: flutter pub get to install the needed packages.

https://gist.github.com/nkenna/59203e5b9daf1f61009ece4aac665fba

From line 11, since the app is a websocket client. It needs the link/channel to the server.

https://gist.github.com/nkenna/5a0d56941c2d7f0658f8aa09a62fc0f9

From line 5 and 14, temperature and humidity values are requested from the server at intervals. The content of the message sent to the server is usually temperature or humidity so that the server can interpret it perfectly.

https://gist.github.com/nkenna/b782e1c7a0f6f1d4780658feba0dee10

To control devices, predefined messages like frontlite1 [ON] and frontlite [OFF] are sent to the server. These type of messages are also sent for other devices. In lines 6 and 9, the widget have to be rebuilt in order to reflect the changes.

https://gist.github.com/nkenna/7c346df8acdd23c23497efc92e920a7b

https://gist.github.com/nkenna/7c346df8acdd23c23497efc92e920a7b

We can use use the webview widget to view the realtime camera feed from our remote camera. It should be noted that the Websocket server and camera feed server is running from a Raspberry Pi 3. This will be part of the next tutorial post in this series. Feel free to drop comments if you have any issues and stay tuned for the next post.

The github repo for this tutorial post is available HERE.

LEAVE A REPLY

Please enter your comment!
Please enter your name here