Connect a Flutter Application to a WebSocket

Tiempo de lectura: 2 minutos

Today we are going to learn how we can connect a Flutter APP to a WebSocket quickly and simply.

Step 1: Flutter Project Setup

  1. Create a new Flutter project using the following command in your terminal:
   flutter create my_app

Replace “my_app” with the name you want for your project.

We will use the web_socket_channel library: https://pub.dev/packages/web_socket_channel

To add the dependency, run:

flutter pub add web_socket_channel

Run flutter pub get to install the dependencies.

Socket Configuration:

Create the file named websocket_service.dart

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

class WebSocketService {
  late WebSocketChannel _channel;

  WebSocketService(Uri wsUrl) {
    _channel = WebSocketChannel.connect(wsUrl);
    _initWebSocket();
  }

  WebSocketChannel get channel => _channel;

  void _initWebSocket() async {
    await _channel.sink.done;
    print('WebSocket closed with code: ${_channel.closeCode}');
  }

  void sendMessage(String message) {
    _channel.sink.add(message);
  }

  void closeConnection() {
    _channel.sink.close(status.goingAway);
  }
}

Flutter UI Configuration

Replace the contents of the lib/main.dart file with the following Flutter code:

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

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

class MyApp extends StatelessWidget {
  final wsUrl = Uri.parse('ws://example.com'); // Replace with your WebSocket server URL

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('WebSocket Flutter'),
        ),
        body: MyWebSocketScreen(
          webSocketService: WebSocketService(wsUrl),
        ),
      ),
    );
  }
}

class MyWebSocketScreen extends StatefulWidget {
  final WebSocketService webSocketService;

  MyWebSocketScreen({required this.webSocketService});

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

class _MyWebSocketScreenState extends State {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: widget.webSocketService.channel.stream,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }

        if (snapshot.connectionState == ConnectionState.done) {
          return Text('Connection Closed');
        }

        if (snapshot.hasData) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Received: ${snapshot.data}'),
              ElevatedButton(
                onPressed: () {
                  widget.webSocketService.sendMessage('Hello from Flutter');
                },
                child: Text('Send Message'),
              ),
            ],
          );
        }

        return Text('Connected to WebSocket');
      },
    );
  }

  @override
  void dispose() {
    widget.webSocketService.closeConnection();
    super.dispose();
  }
}

Make sure to adjust the WebSocket URL (IOWebSocketChannel.connect) to match your FastAPI server address.

Step 3: Run the Flutter Application

  1. Open your terminal and navigate to your Flutter project directory:
   cd my_app
  1. Run your Flutter application:
   flutter run

This will start your Flutter application and connect it to the FastAPI server via WebSocket. The application will display the connection status and allow sending messages to the server.

That’s it! Now you have a Flutter application connected to a FastAPI server via WebSocket.

Leave a Comment