Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 73 ยท Networking and data

WebSockets and Realtime Data

Learn realtime Flutter apps: web_socket_channel, turning a socket into a Stream for the UI, reconnecting with backoff, and Firebase-style snapshot listeners.

HTTP is a question and an answer: the app asks, the server replies, the connection is done. That is fine for loading a product list, but poor for a chat, a live score, a stock ticker or a multiplayer game, where the server has news and should be able to speak first. A WebSocket keeps one connection open so both sides can send messages at any time.

In Flutter a WebSocket is naturally a Stream for incoming messages and a sink for outgoing ones. This lesson shows the web_socket_channel package, how to connect it to the UI, how to reconnect after a dropped connection, and how Firebase-style listeners fit the same idea. It builds on FutureBuilder, StreamBuilder and Async UI and Futures, async/await and Streams.

Real vs stand-in. The Dart is real Flutter code, read-only here, because the lessons cannot open real sockets from Dart. The live examples are JavaScript stand-ins: a fake server that pushes events, an async iterator that behaves like a Stream, and a reconnect loop with backoff.

Request vs open connection

HTTP The app asks, the server answers.
WebSocket One open pipe, both directions.
Push The server speaks first.
1 / 2

web_socket_channel

Add the package with flutter pub add web_socket_channel. A channel exposes stream for incoming data and sink for outgoing data:

DART
import 'package:web_socket_channel/web_socket_channel.dart';

final channel = WebSocketChannel.connect(Uri.parse('wss://chat.example.com/room/42'));

await channel.ready;                      // completes when the connection is open

channel.sink.add('{"type":"hello"}');     // send

channel.stream.listen(
  (message) => print('got: $message'),    // receive
  onError: (error) => print('error: $error'),
  onDone: () => print('closed with ${channel.closeCode}'),
);

// later
await channel.sink.close();

Use wss:// (encrypted) for anything real, just as you use https://. Messages are String or binary List<int>; JSON text is the usual choice, decoded with jsonDecode as in HTTP Requests and JSON. channel.ready is a Future that fails if the connection cannot be opened, so await it inside a try.

A channel's stream is a single-subscription stream: you may only listen once. If two widgets need the messages, share them through one object (a repository or notifier) that listens once and re-publishes with a broadcast controller.

Messages become UI

Because the channel is a stream, StreamBuilder works directly for simple cases:

DART
StreamBuilder(
  stream: channel.stream,
  builder: (context, snapshot) {
    if (snapshot.hasError) return Text('Error: ${snapshot.error}');
    return Text(snapshot.hasData ? '${snapshot.data}' : 'Waiting for the first message...');
  },
)

That shows only the latest message. A chat needs the whole list. The clean approach is a small class that owns the socket, keeps the list and notifies listeners:

DART
class ChatClient extends ChangeNotifier {
  final List<ChatMessage> messages = [];
  WebSocketChannel? _channel;
  StreamSubscription<dynamic>? _subscription;

  void connect() {
    _channel = WebSocketChannel.connect(Uri.parse('wss://chat.example.com/room/42'));
    _subscription = _channel!.stream.listen((raw) {
      messages.add(ChatMessage.fromJson(jsonDecode(raw as String) as Map<String, dynamic>));
      notifyListeners();
    });
  }

  void send(String text) {
    _channel?.sink.add(jsonEncode({'type': 'message', 'text': text}));
  }

  @override
  void dispose() {
    _subscription?.cancel();
    _channel?.sink.close();
    super.dispose();
  }
}

The UI listens to the ChangeNotifier (see Lifting State Up and ValueNotifier). The most important line is dispose: forgetting to close a channel keeps a connection and a subscription alive after the screen has gone.

Stand-in: a stream of server events

Here a fake server pushes events and an async generator plays the role of channel.stream. The consumer uses for await, the same idea as listen in Dart.

JS A server that speaks first

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The client never asked for any of these events. It only listened. Notice that the typing event updates a different piece of UI state than a message: realtime protocols usually carry a type field so the client can route each event.

Reconnecting

Mobile connections drop all the time: the train enters a tunnel, the phone switches from Wi-Fi to mobile data, the server restarts. A realtime screen must detect the close and try again. Retrying immediately in a tight loop hammers the server, so use exponential backoff with a cap, plus some randomness so thousands of clients do not all return at the same second.

DART
Future<void> _connectWithRetry() async {
  var attempt = 0;
  while (!_disposed) {
    try {
      final channel = WebSocketChannel.connect(_uri);
      await channel.ready;
      attempt = 0;                                   // success resets the counter
      await for (final message in channel.stream) {
        _handle(message);
      }
    } catch (e) {
      // fall through to the delay below
    }
    if (_disposed) return;
    final seconds = min(30, pow(2, attempt).toInt());
    final jitter = Random().nextInt(1000);
    await Future<void>.delayed(Duration(seconds: seconds, milliseconds: jitter));
    attempt++;
  }
}

Also think about what the user sees: show a "Reconnecting..." banner, queue outgoing messages (or disable the send button), and after reconnecting ask the server for what you missed (a "messages since id 120" request over HTTP is a common choice). Sending a periodic ping message, and treating silence as a dead connection, catches half-open connections that never report onDone.

JS Backoff delays and a reconnect loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The delays 1, 2, 4, 8, 16, 30, 30 show the cap. Without a cap the wait would reach minutes after a few more failures.

Firebase-style listeners

Firebase Firestore and the Realtime Database do not expose a socket. They give you a stream of snapshots instead, and the SDK handles the connection, offline cache and reconnects for you:

DART
final query = FirebaseFirestore.instance
    .collection('rooms/42/messages')
    .orderBy('sentAt')
    .limitToLast(50);

StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
  stream: query.snapshots(),
  builder: (context, snapshot) {
    if (snapshot.hasError) return const Text('Something went wrong');
    if (!snapshot.hasData) return const CircularProgressIndicator();
    final docs = snapshot.requireData.docs;
    return ListView(
      children: [for (final doc in docs) ListTile(title: Text(doc['text'] as String))],
    );
  },
)

Every change on the server produces a new snapshot containing the full result, so the same StreamBuilder pattern applies. The trade-off: you rely on a vendor, but you skip writing the server, protocol and reconnect logic. Setup and security rules are covered in Firebase: Auth, Firestore and Cloud Messaging. For a custom server, alternatives built on top of WebSockets (Socket.IO clients, GraphQL subscriptions, Server-Sent Events for one-way feeds) exist; choose by what your backend offers.

Pitfalls

  • Not closing the channel when the screen is disposed.
  • Listening twice to a single-subscription stream.
  • Parsing without checks. A malformed message should be logged and skipped, not crash the stream.
  • Updating the UI too often. A feed of hundreds of events per second should be batched (collect for 100 ms, then notify once).
  • Background limits. Mobile systems pause sockets when the app is backgrounded; use push notifications for important messages (see Camera, Location, Permissions and Notifications).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use a WebSocket instead of repeated HTTP requests for a chat?

    A WebSocket keeps a two-way connection open, so the server can speak first without polling.
  2. 2. What type is WebSocketChannel.stream?

    Incoming messages are a Stream. It can be listened to only once unless you convert it to a broadcast stream.
  3. 3. Why add jitter to exponential backoff?

    Random extra delay spreads reconnects out and protects a recovering server.
  4. 4. What should the screen's dispose method do with the channel?

    Unclosed channels keep connections and listeners alive after the widget is gone.
  5. 5. How does Firestore's snapshots() fit a Flutter UI?

    snapshots() emits a new QuerySnapshot whenever data changes, which StreamBuilder can display.

Summary

  • A WebSocket is a long-lived two-way connection; web_socket_channel exposes a stream and a sink.
  • Keep the socket in a client object, accumulate messages there, and close it in dispose.
  • Reconnect with exponential backoff, a cap and jitter, and tell the user while it happens.
  • Streams are single-subscription by default; share data through one listener.
  • Firebase listeners give the same stream-to-UI pattern with the connection handled for you.

Next: Local Storage: SharedPreferences, SQLite and Hive