Skip to content

A Step-By-Step Guide to Building Real-time Apps With Flutter and Web Sockets

A Step-By-Step Guide to Building Real-time Apps With Flutter and WebSockets

Introduction

Have you ever considered the key role of fast app development and real-time features? These are crucial for today’s apps. Many applications rely on the capabilities of real-time. They include messaging, sync stock market prices and providing live notifications. To meet these needs, REST on its own requires many calls to one endpoint. This can be a burden on the server. They have solutions. They allow seamless communication between client and server.

What are Web Sockets

Web sockets are a protocol for communication. They enable real-time, full-duplex communication between a client and server. This happens via an extended, continuous connection. HTTP follows an order-response model. But, Web Socket lets the server and client start data transmission. It lets them create a permanent connection. This connection stays open until shut. This means that both server and client can talk with each other at any point. This gives an uninterrupted, real-time experience.

What are WebSockets Used For?

Web socketsWeb Sockets begin continuous, two-way communication. It is between your client and Web Socket server. This eliminates traffic. A single connection can send data. It gives speed and real-time experience on the internet. Web Sockets let servers track clients. They can send them info when needed. HTTP can’t do this. Web Sockets have many uses. They are vital for real-time communications. For example:

  • Chat Applications
  • Multiplayer Online Games
  • Financial Trading Platforms
  • Live Sports Updates
  • Live Collaboration Tools
  • Real-time Monitoring and Tracking Systems

Support For WebSockets using Flutter

Flutter provides extensive support for Web Sockets using WebSocketIO class. It is important to keep in mind that the class depends on ‘dart.io and ‘dart:html. We can’t build for mobile and web at the same time. Dart’s team has come up with the ‘web_socket_channel’ to address this issue. It integrates both libraries so that they can work well on cross-platform development.

Setting up the Dart Server project

Let’s begin by creating the new Dart SDK. First, ensure that you are running the most recent version of Dart SDK in place. In your terminal, run these commands:

dart create -t server-shelf web_socket_server
cd web_socket_server

Creating WebSocket Server to listen to websocket IO request

Let’s begin by studying the Dart server’s code, which is capable of continuously monitoring WebSocket IO requests directed towards it, and ensuring an efficient handling of these requests.

                        
                            void main(List args) async {
                                // Use any available host or container IP (usually `0.0.0.0`).
                                var server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
                                print('WebSocket server listening on ${server.address}:${server.port}');
                               
                                await for (var request in server) {
                                 //receive the websocket request
                                 WebSocketTransformer.upgrade(request).then(
                                  (webSocket) async {
                                   print('Client connected');
                                  },
                                 );
                                }
                               }
                               
                        
                    

Let’s then add technology to send information via our servers to the client. In Particular, we’ll send prices for various cryptocurrency coins to the client to check. The prices update every second. This allows for real-time testing of our client connection. A function generates random prices for five coins. The prices range between 100 to 200.

                            
                                List> generateRandomPrices() {
                                    final List cryptocurrencies = [
                                     'Bitcoin',
                                     'Ethereum',
                                     'Ripple',
                                     'Litecoin',
                                     'Cardano'
                                    ];
                                    final Random random = Random();
                                   
                                    List> prices = cryptocurrencies.map(
                                     (crypto) {
                                      // Random price between 100 and 200
                                      double price = 100.0 + random.nextDouble() * 100.0;
                                      return {
                                       'name': crypto,
                                       'symbol': crypto.substring(0, 3),
                                       'price': price.toStringAsFixed(2)
                                      };
                                     },
                                    ).toList();
                                   
                                    return prices;
                                   }
                                   
                            
                        

We also added a more delay of 3 seconds in the initial request to control the loading behavior . To launch the dart server start by running the following command from your terminal:

                        
                            WebSocketTransformer.upgrade(request).then(
   (webSocket) async {
    print('Client connected');
    // Fetch initial cryptocurrency prices with a delay of 3 seconds to show loading
    await Future.delayed(
     Duration(seconds: 3),
    );
    List> initialPrices = generateRandomPrices();
    webSocket.add(
     json_Encode(initialPrices),
    );
    // Set up a timer to update prices every second
    Timer.periodic(
     Duration(seconds: 1),
     (timer) {
      List> updatedPrices =  generateRandomPrices();
      webSocket.add(
       json_Encode(updatedPrices),
      );
     },
    );
    webSocket.listen(
     (data) {
      // You can add custom logic for handling client messages here
      print('Received data: $data');
     },
     onDone: () {
      print('Client disconnected');
     },
    );
   },
  )

                        
                    

Setting up the Flutter project

To start the creation of a brand new Flutter project, it’s essential to have the latest Flutter SDK in place. Go to your terminal, and then execute the following commands:

flutter create web_socket_client
cd web_socket_client

Adding WebSocket IO Dependencies

To use websockets within Dart we need to integrate websockets and the web_socket_channel package into our Dart project. Browse through the ‘pubspec.yaml’ file in your program’s source. Make sure to incorporate the following line:

dependencies:
web_socket_channel: ^2.4.0
Be sure to run the command “flutter pub get” in your console. This will get and install the latest dependencies.

Connecting to a WebSocket

Once we finish setting up the project, we can make a simple application. It will connect to a Web Socket channel.

                        
                            import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() => runApp(WebSocketApp());

class WebSocketApp extends StatelessWidget {
 final WebSocketChannel channel = WebSocketChannel.connect(
  Uri.parse('ws://192.168.3.243:8080'),
 );

 WebSocketApp({super.key});

 @override
 Widget build(BuildContext context) {
  return MaterialApp(
   home: Scaffold(
    appBar: AppBar(
     title: const Text('Crypto Tracker'),
    ),
    body: Container(),
   ),
  );

                        
                    

Web Socket URLs generally start by a “ws:” or “wss:”. We’re now ready to use the new data. It is connected through Web Socket. Have you considered how to show and update the data? New information will come from the servers.

To solve this issue, we’ll make use of Flutter’s inbuilt Stream Builder widget. The widget can refresh data when it spots new information in this data stream. Web Socket uses an info stream. It allows the exchange of info in both directions. This is vital for real-time apps.

Building a Real-Time Feature

                    
                        Now, we are building the StreamBuilder widget. It will receive the information from our Websocket and show it.

import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() => runApp(WebSocketApp());

class WebSocketApp extends StatelessWidget {
 final WebSocketChannel channel = WebSocketChannel.connect(
  // here the url can be replaced with your own websocket url
  Uri.parse('ws://192.168.3.243:8080'),
 );

 WebSocketApp({super.key});

 @override
 Widget build(BuildContext context) {
  return MaterialApp(
   home: Scaffold(
    appBar: AppBar(
     title: const Text('Crypto Tracker'),
    ),
    body: StreamBuilder(
     stream: channel.stream,
     builder: (context, snapshot) {
      if (snapshot.hasData) {
       List body = json_Decode(snapshot.data);
       return ListView.builder(
        shrinkWrap: true,
        itemCount: body.length,
        itemBuilder: (context, index) => ListTile(
         leading: Text(
          body[index]["symbol"],
         ),
         title: Text(
          body[index]["name"],
         ),
         trailing: Text(
          '₹${body[index]["price"]}',
         ),
        ),
       );
      } else if (snapshot.hasError) {
       return Center(
        child: Text(
         'Error Connecting : ${snapshot.error.toString()}',
        ),
       );
      } else {
       return Center(
        child: Platform.isIOS
          ? const CupertinoActivityIndicator()
          : const CircularProgressIndicator(),
       );
      }
     },
    ),
   ),
  );
 }
}

                    
                

The app is a simple one that connects to the WebSocket by using the StreamBuilder widget. It then shows the data received via the web server.

 

Frequently Asked Questions (FAQs)

Flutter is an open-source UI software kit. Google made it for building native apps. It can compile for mobile, web, and desktop from a single codebase. It allows developers to create beautiful and fast user experiences across different platforms.
WebSockets is a protocol. It provides full-duplex channels over one TCP connection. It allows a client to talk in real-time with a server. This enables the exchange of data in both directions.
Flutter provides a strong framework. It is for making real-time apps that work on many platforms. You can use a single codebase. Its fast rendering engine. Its customizable widgets make it good for building responsive and interactive user interfaces. Also, Flutter’s hot reload feature lets developers iterate on their code. It makes the development process faster.
  • Low latency: Web Sockets provide a persistent connection between the client and server, reducing the overhead of establishing new connections for each request.
  • Bidirectional communication: Web Sockets allow data to be sent and received simultaneously, enabling real-time updates without the need for polling.
  • Scalability: Web Sockets support a large number of concurrent connections, making them suitable for applications with high traffic volumes.
  • Efficiency: Web Sockets use a lightweight protocol that minimizes overhead, resulting in faster communication compared to traditional HTTP requests.
  • Flutter and WebSockets can build many real-time apps. These include:
  • Chat applications are real-time messaging apps. They let users send and receive messages instantly.
  • These are collaborative editing tools. They are apps that let many users work together on documents or projects in real time.
  • Live tracking apps track and display real-time data. This data may be location tracking or stock updates.
  • These are multiplayer games. They are real-time games that support multiplayer interactions. This includes multiplayer online games and real-time strategy games.
  • The steps involved in building real-time apps with Flutter and WebSockets include:
  • Setting up a WebSocket server involves making a server with a technology like Node.js, Python, or Go.
  • Integrating WebSockets with Flutter is about using a WebSocket client library to connect. It connects the Flutter app to the WebSocket server.
  • Handling real-time events involves adding logic in the Flutter app. This logic sends and receives real-time data via WebSockets. It updates UI elements and processes incoming messages.
  • Testing and debugging are about testing the app’s real-time functionality. The aim is to send data. And also that the app behaves as expected in real-time.
Many online resources can teach you to build real-time apps. They use Flutter and WebSockets. These resources include tutorials, documentation, and forums. The Flutter website offers valuable resources. Other platforms like GitHub and Stack Overflow do too. They are for developers. They want to explore making real-time apps with Flutter and WebSockets. Also, many Flutter packages can add WebSockets to Flutter apps. They make it easier to start real-time development
0 +
Projects
0 +
Clients
0 +
Years of Experience
0 +
Startups

WANT TO START A PROJECT?