How to Connect Sockets in Flutter: A Comprehensive Guide | by Arun Pradhan

Arun Pradhan
4 min readSep 15, 2023

--

Connect Sockets in Flutter

Sockets play a crucial role in modern app development, enabling real-time communication between devices and servers. Flutter, with its rich ecosystem and versatility, provides developers with the tools to implement socket connections seamlessly. In this guide, we’ll walk you through the process of connecting sockets in a Flutter application.

Understanding Sockets

Before diving into the code, let’s clarify what sockets are and why they are important. Sockets are communication endpoints that allow bidirectional data transfer between a client and a server. They enable real-time data exchange and are commonly used in applications that require instant updates, such as chat apps, online games, and live streaming services.

In Flutter, you can establish socket connections using various packages, but one of the most popular choices is the `socket_io_client` package. It provides a convenient way to connect to WebSocket and Socket.IO servers.

Setting Up Your Flutter Project :

Add the `socket_io_client` package to your `pubspec.yaml` file:

dependencies:
socket_io_client: ^2.0.3+1

Run `flutter pub get` to fetch and install the package.

Establishing a Socket Connection

Now that your project is set up, let’s establish a socket connection. In this example, we’ll connect to a Socket.IO server, but you can adapt the code for WebSocket or other socket types as needed.

  1. Import the necessary package in your Dart file:
 import 'package:socket_io_client/socket_io_client.dart' as io;

2. Create a function to establish the socket connection:

 void connectToSocket() {
// Replace 'https://your_socket_server_url' with the URL of your Socket.IO server.
final socket = io.io('https://your_socket_server_url', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});

socket.connect();

socket.onConnect((_) {
print('Connected to the socket server');
});

socket.onDisconnect((_) {
print('Disconnected from the socket server');
});

socket.on('message', (data) {
print('Received message: $data');
});

// Add more event listeners and functionality as needed.

// To send a message to the server, use:
// socket.emit('eventName', 'message data');
}

3. Call the `connectToSocket` function when needed in your app, for example, in the `initState` of a widget:

 @override
void initState() {
super.initState();
connectToSocket();
}

Handling Socket Events

In the `connectToSocket` function, we’ve set up listeners for various socket events such as `onConnect`, `onDisconnect`, and `on(‘message’)`. You can add more event listeners based on your server’s events and requirements.

To send messages or data to the server, use the `emit` method:

socket.emit('eventName', 'message data');

Replace `’eventName’` with the actual event name your server expects, and `’message data’` with the data you want to send.

FullCode :

import 'package:flutter/material.dart';
import 'package:socket_io_client/socket_io_client.dart' as io;

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SocketIOExample(),
);
}
}

class SocketIOExample extends StatefulWidget {
@override
_SocketIOExampleState createState() => _SocketIOExampleState();
}

class _SocketIOExampleState extends State<SocketIOExample> {
final String serverUrl = 'https://your_socket_server_url';
late io.Socket socket;
TextEditingController messageController = TextEditingController();
List<String> messages = [];

@override
void initState() {
super.initState();

// Initialize and connect to the socket server.
socket = io.io(serverUrl, <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});

socket.connect();

// Event listeners.
socket.onConnect((_) {
print('Connected to the socket server');
});

socket.onDisconnect((_) {
print('Disconnected from the socket server');
});

socket.on('message', (data) {
setState(() {
messages.add(data);
});
});
}

// Function to send a message to the server.
void sendMessage() {
String message = messageController.text;
if (message.isNotEmpty) {
socket.emit('chatMessage', message);
messageController.clear();
}
}

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

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Socket.IO Chat Example'),
),
body: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(messages[index]),
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: TextField(
controller: messageController,
decoration: InputDecoration(
hintText: 'Enter your message',
),
),
),
IconButton(
icon: Icon(Icons.send),
onPressed: sendMessage,
),
],
),
),
],
),
);
}
}

Conclusion

Connecting sockets in Flutter allows you to build real-time, interactive features in your apps. With the `socket_io_client` package, you can easily establish connections to Socket.IO servers and handle events efficiently. Remember to adapt the code to your specific server requirements, and you’ll be on your way to building dynamic, real-time applications in no time. Happy coding!

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

--

--

Arun Pradhan

Arun Pradhan, Flutter developer having 3.5 years of experience in Mobile application development. FLUTTER | ANDROID | IOS