Working with WebSocket
Explore how to build real-time communication in Flutter using WebSocket. Understand connecting to a WebSocket server, sending and receiving messages with Streams, and properly closing connections to avoid memory leaks. This lesson guides you through practical implementation for responsive networking in your apps.
Introduction
There might be cases where we need to implement real-time communication in Flutter—for example, when building a chat or stock trading application. WebSocket offers real-time two-way communication between clients and servers.
The alternative to WebSocket is polling, where instead of delivering messages in real-time to the client, the clients keep checking the server after a time interval. Polling is an option that could work for your application, but this takes a lot of computing resources, especially on mobile, which will drain the device’s battery.
We’ll work on the following app in this lesson:
name: websockets
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
# TODO-1: Add packages
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^1.0.0
flutter:
uses-material-design: true