Sockets in Flutter, reading this first thing that comes to our mind in What is Socket? Why do we need them?
So, In this blog, we will be answering all these questions and will also have a quick and easy integration of Socket in our Flutter application.
Looking out for some best Flutter App Development Services.
Let’s begin reading about the Sockets…
The Socket is a way to spawn two-way communication between the Client and Server. In the socket, the transmission of data happens in real time.
The basic steps to integrate the Socket are as follows-
- Connect to a socket
- Receive a message from Server
- Send a message from Client to Server.
- Close the socket.
Here’s a socket_io_client package with the help of which we will be integrating Socket into our app.
Steps for Working with Sockets in Flutter
Firstly, we will need to add the dependency in the pubspec.yaml file
1 |
socket_io_client: ^2.0.2 |
Now, we will need to import the package to our file
1 |
import 'package:socket_io_client/socket_io_client.dart' as socket_io; |
Starting with connecting the socket with the server, we need to setup with the host
1 2 3 4 5 6 7 |
socket_io.Socket? socket = socket_io .io($HOST_URL), <String, dynamic>{ 'transports': ['websocket'], 'reconnection': true, 'autoConnect': true }); socket.connect(); |
If the socket connection fails, you might need to add the code in the AndroidManifest.xml file
1 2 |
<application android:usesCleartextTraffic="true"> |
Once the connection is established, we have onConnect callback in which we can add the methods for listening to the changes from Server or send a message to the server.
In order to listen to the changes, we will use a socket.on() method.
1 |
socket.on('message-received', (data) => print(data)); |
Here, ‘message-received’ is the event name whereas in the function we can specify whatever we want to do after listening to the changes.
After listening to the changes, we might need to emit the event from our end, for that we have a socket.emit() method.
1 |
socket.emit('send-message',{"roomID": "123"}); |
Here, ‘send-message’ is the event name and the second parameter takes the dynamic data which we send from the Client to the Server end.
At last, we need to make sure that we dispose of the socket connection.
1 2 3 4 5 |
@override void dispose() { socket.dispose(); super.dispose(); } |
Conclusion
In this blog, we have discussed Working with Sockets in Flutter.
I hope it will help you understand.
Read more interesting Flutter Blogs by Mobikul.
Thanks for reading!!
References
https://medium.com/flutter-community/flutter-integrating-socket-io-client-2a8f6e208810