WebSockets in Flutter: solved exercise with web_socket_channel

WebSockets in Flutter: solved exercise with web_socket_channel

WebSockets allow persistent, bidirectional communication between client and server. Unlike HTTP, the server can push data without the client requesting it. They are ideal for chats, price feeds, live notifications, and multiplayer games.

Problem statement

Implement a real-time price ticker that:

  • Connects to a WebSocket server.
  • Displays price updates with StreamBuilder.
  • Allows subscribing and unsubscribing to symbols (BTC, ETH, SOL).
  • Manages automatic reconnection with exponential backoff.
  • Shows connection state (connecting, connected, disconnected, error).

Dependencies

1
2
3
4
5
# pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  web_socket_channel: ^3.0.1

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() => runApp(const MaterialApp(home: PriceTicker()));

// ── Models ─────────────────────────────────────────────────────────────────────
enum ConnectionState { connecting, connected, disconnected, error }

class PriceUpdate {
  final String symbol;
  final double price;
  final double change;  // percentage change from previous price
  final DateTime timestamp;

  PriceUpdate({
    required this.symbol,
    required this.price,
    required this.change,
    required this.timestamp,
  });

  factory PriceUpdate.fromJson(Map<String, dynamic> json) => PriceUpdate(
        symbol: json['symbol'] as String,
        price: (json['price'] as num).toDouble(),
        change: (json['change'] as num).toDouble(),
        timestamp: DateTime.parse(json['ts'] as String),
      );
}

// ── WebSocket service with reconnection ────────────────────────────────────────
class PriceWebSocketService {
  // For real use you can connect to wss://stream.binance.com:9443/ws
  // Here we use a public echo server and simulate data locally
  static const _wsUrl = 'wss://echo.websocket.org';

  WebSocketChannel? _channel;
  StreamController<PriceUpdate>? _priceController;
  Timer? _reconnectTimer;
  Timer? _simulatorTimer;
  int _retryCount = 0;
  bool _disposed = false;

  // Connection state exposed as ValueNotifier
  final connectionState = ValueNotifier(ConnectionState.disconnected);

  Stream<PriceUpdate> get priceStream =>
      (_priceController ??= StreamController.broadcast()).stream;

  final _subscriptions = <String>{};
  final _prices = <String, double>{'BTC': 65000, 'ETH': 3200, 'SOL': 145};

  void connect() {
    if (_disposed) return;
    _priceController ??= StreamController.broadcast();
    connectionState.value = ConnectionState.connecting;

    try {
      _channel = WebSocketChannel.connect(Uri.parse(_wsUrl));
      _channel!.ready.then((_) {
        if (_disposed) return;
        connectionState.value = ConnectionState.connected;
        _retryCount = 0;
        // Re-send active subscriptions
        for (final symbol in _subscriptions) {
          _sendSubscribe(symbol);
        }
        // On a real server we would listen to _channel!.stream
        // Here we simulate updates locally for the example
        _startSimulator();
      }).catchError(_handleError);
    } catch (e) {
      _handleError(e);
    }
  }

  void subscribe(String symbol) {
    _subscriptions.add(symbol);
    if (connectionState.value == ConnectionState.connected) {
      _sendSubscribe(symbol);
    }
  }

  void unsubscribe(String symbol) {
    _subscriptions.remove(symbol);
    if (connectionState.value == ConnectionState.connected) {
      _channel?.sink.add(jsonEncode({'action': 'unsubscribe', 'symbol': symbol}));
    }
  }

  void _sendSubscribe(String symbol) {
    _channel?.sink.add(jsonEncode({'action': 'subscribe', 'symbol': symbol}));
  }

  void _startSimulator() {
    _simulatorTimer?.cancel();
    final rng = Random();
    _simulatorTimer = Timer.periodic(const Duration(seconds: 1), (_) {
      for (final symbol in _subscriptions) {
        final prev = _prices[symbol]!;
        final delta = (rng.nextDouble() - 0.49) * prev * 0.005;
        final newPrice = prev + delta;
        _prices[symbol] = newPrice;
        _priceController?.add(PriceUpdate(
          symbol: symbol,
          price: newPrice,
          change: delta / prev * 100,
          timestamp: DateTime.now(),
        ));
      }
    });
  }

  void _handleError(dynamic error) {
    if (_disposed) return;
    connectionState.value = ConnectionState.error;
    _simulatorTimer?.cancel();
    _scheduleReconnect();
  }

  void _scheduleReconnect() {
    _reconnectTimer?.cancel();
    final delay = Duration(seconds: min(30, pow(2, _retryCount).toInt()));
    _retryCount++;
    _reconnectTimer = Timer(delay, connect);
  }

  void disconnect() {
    _reconnectTimer?.cancel();
    _simulatorTimer?.cancel();
    _channel?.sink.close();
    connectionState.value = ConnectionState.disconnected;
  }

  void dispose() {
    _disposed = true;
    disconnect();
    _priceController?.close();
  }
}

// ── Main screen ────────────────────────────────────────────────────────────────
class PriceTicker extends StatefulWidget {
  const PriceTicker({super.key});
  @override
  State<PriceTicker> createState() => _PriceTickerState();
}

class _PriceTickerState extends State<PriceTicker> {
  final _service = PriceWebSocketService();
  final _latestPrices = <String, PriceUpdate>{};
  StreamSubscription<PriceUpdate>? _sub;

  @override
  void initState() {
    super.initState();
    _service.connect();
    for (final s in ['BTC', 'ETH', 'SOL']) {
      _service.subscribe(s);
    }
    _sub = _service.priceStream.listen((update) {
      if (mounted) setState(() => _latestPrices[update.symbol] = update);
    });
  }

  @override
  void dispose() {
    _sub?.cancel();
    _service.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Real-time ticker'),
        actions: [
          ValueListenableBuilder(
            valueListenable: _service.connectionState,
            builder: (_, state, __) => Padding(
              padding: const EdgeInsets.only(right: 16),
              child: _ConnectionBadge(state: state),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: _latestPrices.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : ListView(
                    padding: const EdgeInsets.all(12),
                    children: _latestPrices.values
                        .map((u) => _PriceCard(update: u))
                        .toList(),
                  ),
          ),
          _SubscriptionPanel(service: _service),
        ],
      ),
    );
  }
}

// ── Widgets ────────────────────────────────────────────────────────────────────
class _ConnectionBadge extends StatelessWidget {
  final ConnectionState state;
  const _ConnectionBadge({required this.state});

  @override
  Widget build(BuildContext context) {
    final (label, color) = switch (state) {
      ConnectionState.connected => ('● Connected', Colors.green),
      ConnectionState.connecting => ('● Connecting…', Colors.orange),
      ConnectionState.error => ('● Error', Colors.red),
      ConnectionState.disconnected => ('● Disconnected', Colors.grey),
    };
    return Text(label, style: TextStyle(color: color, fontSize: 12));
  }
}

class _PriceCard extends StatelessWidget {
  final PriceUpdate update;
  const _PriceCard({required this.update});

  @override
  Widget build(BuildContext context) {
    final isUp = update.change >= 0;
    return Card(
      child: ListTile(
        leading: CircleAvatar(child: Text(update.symbol[0])),
        title: Text(update.symbol,
            style: const TextStyle(fontWeight: FontWeight.bold)),
        subtitle: Text(
            '${TimeOfDay.fromDateTime(update.timestamp).format(context)}'),
        trailing: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '\$${update.price.toStringAsFixed(2)}',
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Text(
              '${isUp ? '+' : ''}${update.change.toStringAsFixed(3)}%',
              style: TextStyle(
                  color: isUp ? Colors.green : Colors.red, fontSize: 12),
            ),
          ],
        ),
      ),
    );
  }
}

class _SubscriptionPanel extends StatefulWidget {
  final PriceWebSocketService service;
  const _SubscriptionPanel({required this.service});
  @override
  State<_SubscriptionPanel> createState() => _SubscriptionPanelState();
}

class _SubscriptionPanelState extends State<_SubscriptionPanel> {
  final _active = {'BTC', 'ETH', 'SOL'};
  static const _available = ['BTC', 'ETH', 'SOL', 'ADA', 'DOT', 'AVAX'];

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        border: Border(top: BorderSide(color: Colors.grey.shade300)),
      ),
      child: Wrap(
        spacing: 8,
        children: _available.map((symbol) {
          final isActive = _active.contains(symbol);
          return FilterChip(
            label: Text(symbol),
            selected: isActive,
            onSelected: (selected) {
              setState(() {
                if (selected) {
                  _active.add(symbol);
                  widget.service.subscribe(symbol);
                } else {
                  _active.remove(symbol);
                  widget.service.unsubscribe(symbol);
                }
              });
            },
          );
        }).toList(),
      ),
    );
  }
}

Exponential backoff reconnection

1
2
3
4
5
6
void _scheduleReconnect() {
  // Waits 1s, 2s, 4s, 8s… up to 30s maximum
  final delay = Duration(seconds: min(30, pow(2, _retryCount).toInt()));
  _retryCount++;
  _reconnectTimer = Timer(delay, connect);
}

Exponential backoff avoids overwhelming the server with immediate reconnections during a sustained failure.

Common mistakes

  • Not closing the sink on widget unmount: causes memory leaks. Always call channel.sink.close() in dispose().
  • StreamSubscription not cancelled: just like any Stream, cancel the subscription in dispose.
  • Insecure WebSocket in production: use wss:// (TLS) in production. Plain-text ws:// is not acceptable for sensitive data.

Practical use

WebSockets are used in: chats (WhatsApp Web, Slack), financial feeds (Binance, Coinbase), real-time dashboards, multiplayer games, real-time collaboration (Google Docs, Figma).

Guided practice and next step

FAQ

Can I use WebSockets with Riverpod or BLoC?

Yes. Convert the channel’s Stream into a Riverpod StreamProvider or into a Stream that your BLoC listens to with on<Event>. The WebSocket channel lives in the repository, outside the BLoC.

What is the difference between WebSocket and Server-Sent Events (SSE)?

SSE is one-directional (server β†’ client), HTTP-based, and simpler. WebSocket is bidirectional and more efficient for frequent two-way communication. Use SSE for read-only news or price feeds; WebSocket for chat or games.

How do I handle authentication in WebSockets?

Send the token in the upgrade request header or as the first message after connecting. Many servers accept the token as a query param (?token=...) in the WebSocket URL.