NetworkingMedium30 XP4 min read
How do you implement WebSocket communication in Flutter?
TL;DR: Use the web_socket_channel package to connect to a WebSocket server. It returns a WebSocketChannel with a stream (incoming) and sink (outgoing). Wrap in a StreamBuilder or BLoC emit.forEach() for reactive UI updates.
Full Answer
WebSockets enable bidirectional, persistent connections — ideal for chat, live scores, or real-time quiz results. Unlike HTTP, the server can push data to the client without a request.
- ▸web_socket_channel: Official Dart package — works on mobile, web, and desktop
- ▸channel.stream: Incoming messages as a Stream<dynamic>
- ▸channel.sink.add(data): Send a message to the server
- ▸channel.sink.close(): Clean up when done (call in dispose())
⚠️
Always close the WebSocket in dispose(). Forgetting causes memory leaks and the connection stays alive until the OS kills the process.
Code Examples
dartWebSocket with BLoC
Output
// Server pushes events -> Stream -> BLoC emits states // emit.forEach auto-cancels the stream on bloc close
Common Mistakes
- ✗Not reconnecting after connection drop — implement exponential backoff retry logic
- ✗Sending raw strings without a message envelope — use typed message schema for extensibility
Interview Tip
💡
Show the full lifecycle: connect in BLoC event, react to stream via emit.forEach, disconnect in close(). Mention that web_socket_channel works on all Flutter platforms including Web.
#websocket#real-time#web-socket-channel#stream