WebSockets in Flutter — Building Real-Time Applications

WebSockets in Flutter — Building Real-Time Applications

FlutterPulse

This article was translated specially for the channel FlutterPulseYou'll find lots of interesting things related to Flutter on this channel. Don't hesitate to subscribe!🚀

Real-time communication is a game-changer in modern apps, enabling features like live messaging, stock updates, multiplayer gaming, and…

Real-time communication is a game-changer in modern apps, enabling features like live messaging, stock updates, multiplayer gaming, and collaborative tools. In this guide, we'll explore:

✅ What WebSockets are and how they work
✅ How to integrate WebSockets in Flutter
✅ Implementing a real-time chat system using WebSockets
✅ Handling connection states and errors

By the end, you'll be able to build real-time, bidirectional communication in your Flutter apps. 🚀

1. Understanding WebSockets

What are WebSockets?

WebSockets provide a persistent, two-way communication channel between the client and server. Unlike traditional HTTP requests that require polling, WebSockets keep a connection open, allowing the server to push data to the client in real time.

Why Use WebSockets in Flutter?

🔹 Low latency: No need to send repeated HTTP requests.
🔹 Efficient: Uses a single TCP connection instead of multiple HTTP calls.
🔹 Real-time updates: Ideal for chat apps, live notifications, stock tickers, and gaming.

2. Setting Up WebSockets in Flutter

Flutter provides a built-in WebSocket class in the dart:io library, but we will use the web_socket_channel package for better compatibility with both mobile and web.

Step 1: Install Dependencies

Add the package in pubspec.yaml:

dependencies:
flutter:
sdk: flutter
web_socket_channel: ^2.4.0

Run:

flutter pub get

3. Connecting to a WebSocket Server

Step 2: Establish a WebSocket Connection

Create a WebSocket service to manage real-time communication:

import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;

class WebSocketService {
final String socketUrl = "wss://echo.websocket.org"; // Example WebSocket server
late WebSocketChannel channel;

void connect() {
channel = WebSocketChannel.connect(Uri.parse(socketUrl));

// Listen for incoming messages
channel.stream.listen(
(message) {
print("Received: $message");
},
onError: (error) {
print("WebSocket error: $error");
},
onDone: () {
print("WebSocket connection closed.");
},
);
}

void sendMessage(String message) {
channel.sink.add(message);
print("Sent: $message");
}

void disconnect() {
channel.sink.close(status.goingAway);
}
}

How it works:
connect(): Establishes a WebSocket connection.
sendMessage(): Sends a message to the server.
listen(): Receives messages from the server.
disconnect(): Closes the connection when done.

4. Creating a Real-Time Chat UI

Now, let's build a basic UI for a real-time chat application using WebSockets.

Step 3: Creating the Chat Screen

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class ChatScreen extends StatefulWidget {

@override
_ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
final WebSocketChannel channel =
WebSocketChannel.connect(Uri.parse('wss://echo.websocket.org'));
final TextEditingController _controller = TextEditingController();
List<String> messages = [];

void _sendMessage() {
if (_controller.text.isNotEmpty) {
channel.sink.add(_controller.text);
setState(() {
messages.add("You: ${_controller.text}");
});
_controller.clear();
}
}

@override
void initState() {
super.initState();
channel.stream.listen(
(message) {
setState(() {
messages.add("Server: $message");
});
},
onError: (error) => print("Error: $error"),
onDone: () => print("WebSocket closed."),
);
}

@override
void dispose() {
channel.sink.close();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Real-Time Chat")),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(messages[index]),
);
},
),
),
Padding(
padding: EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: "Enter message...",
border: OutlineInputBorder(),
),
),
),
IconButton(
icon: Icon(Icons.send),
onPressed: _sendMessage,
),
],
),
),
],
),
);
}
}

How this chat app works:
✅ Users can type a message and send it via WebSockets.
✅ The server
echoes the message back, simulating real-time interaction.
✅ Messages are displayed in a chat UI dynamically.

5. Handling WebSocket Connection States

WebSockets can disconnect due to network issues. To improve reliability, we need to:

Step 4: Auto-Reconnect WebSockets

Modify the WebSocket service:

void connect() {
channel = WebSocketChannel.connect(Uri.parse(socketUrl));
channel.stream.listen(
(message) {
print("Received: $message");
},
onError: (error) {
print("WebSocket error: $error");
reconnect(); // Try to reconnect
},
onDone: () {
print("WebSocket closed.");
reconnect(); // Auto-reconnect
},
);
}

void reconnect() {
Future.delayed(Duration(seconds: 5), () {
print("Reconnecting...");
connect();
});
}

Now, if the connection drops, it will automatically attempt to reconnect after 5 seconds. 🔄

6. Using WebSockets for Live Notifications

WebSockets can also be used to push notifications in real-time. Example:

void listenForNotifications() {
channel.stream.listen((message) {
showNotification(message);
});
}

void showNotification(String message) {
print("New Notification: $message");
}

Now, any new messages from the server trigger a real-time notification! 🔔

Final Thoughts

By using WebSockets in Flutter, we achieved:
Real-time bidirectional communication
✅ A fully functional chat app using WebSockets
Auto-reconnect mechanism for better reliability
✅ WebSockets for real-time notifications

🔥 What's Next?
🔹 Implement private chat rooms using WebSockets
🔹 Secure WebSocket connections with authentication tokens
🔹 Build multiplayer gaming with WebSockets

If you found this story helpful, you can support me at Buy Me a Coffee!

Report Page