Working with WebSocket

Learn to use WebSocket in Flutter.

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

WebSocket app initial code

Connecting to a WebSocket server

We’ll make use of ...

Get hands-on with 1400+ tech skills courses.