Sunday, January 25, 2026
HomeFlutterHow to use WebSocket in flutter step by step guide

How to use WebSocket in flutter step by step guide

Using WebSockets in Flutter allows you to create real-time communication between the client (Flutter app) and a server. Flutter provides WebSocket support via the web_socket_channel package.

Here’s a step-by-step guide to using WebSockets in Flutter:

Step 1: Add Dependency

Open your pubspec.yaml file and add:

dependencies:
  flutter:
    sdk: flutter
  web_socket_channel: ^2.4.0  # Check for latest version on pub.dev

Then run:

flutter pub get

Step 2: Import the Package

In your Dart file:

import 'package:web_socket_channel/web_socket_channel.dart';

Step 3: Connect to a WebSocket Server

You can connect using:

final channel = WebSocketChannel.connect(
  Uri.parse('wss://echo.websocket.org'), // Replace with your WebSocket server
);

Use ws:// for unencrypted connection and wss:// for secure (SSL/TLS) connection.


Step 4: Listen to Incoming Messages

channel.stream.listen(
  (message) {
    print('Received: $message');
  },
  onError: (error) {
    print('Error: $error');
  },
  onDone: () {
    print('WebSocket closed');
  },
);

Step 5: Send Messages

channel.sink.add('Hello WebSocket!');

Step 6: Close the WebSocket Connection

Always close the socket when you’re done:

channel.sink.close();

Full Example (Minimal App)

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final WebSocketChannel channel = WebSocketChannel.connect(
    Uri.parse('wss://echo.websocket.events'), // Test server
  );

  @override
  Widget build(BuildContext context) {
    final TextEditingController controller = TextEditingController();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('WebSocket Demo')),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              TextField(controller: controller),
              ElevatedButton(
                child: Text('Send'),
                onPressed: () {
                  if (controller.text.isNotEmpty) {
                    channel.sink.add(controller.text);
                  }
                },
              ),
              SizedBox(height: 20),
              StreamBuilder(
                stream: channel.stream,
                builder: (context, snapshot) {
                  return Text(snapshot.hasData ? 'Received: ${snapshot.data}' : '');
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Tips

  • Use StreamBuilder to reactively update your UI with WebSocket messages.
  • Always handle connection errors gracefully.
  • Secure your WebSocket server with authentication if used in production.
  • You can reconnect logic using retry or state management.

Also Read:-

Flutter key points mostly asked in flutter interviews
Dart basic programs mostly asked in interviews

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments