Quick Summary
Real-time communication is pivotal in modern applications, facilitating smooth interaction between clients and servers. Within Flutter, harnessing Dart’s websockets provides a crucial mechanism for real-time data exchange. This article delves into the essentials of websockets and their integration within Flutter, focusing on their significance and practical implementation steps in both Dart server-side and Flutter projects. Explore how “Real Time Apps With Flutter and WebSockets” elevates user experiences.
Have you ever considered the crucial role of swift mobile app development and real-time functionalities in today’s applications? Numerous features rely on real-time capabilities, from messaging to syncing stock market rates and delivering live notifications. Addressing these requirements solely through REST entails repetitive calls to a single endpoint, potentially burdening the server. Fortunately, Real-Time Apps With Flutter and WebSockets offer a solution, facilitating seamless bidirectional communication channels between server and client.
Websockets are a communication protocol that allows for real-time, full-duplex communication between a client and a server over a single, long-lived connection. Unlike the HTTP that abides by a request-response model, a websocket enables the client and server to initiate the data transmission, thereby creating a persistent connection that remains open until explicitly closed. This means that both the client and the server can send messages to each other at any time, delivering a seamless real-time experience.
WebSockets initiate the continuous, full-duplex communication between the client and the WebSocket server. This reduces unnecessary traffic, as data can immediately travel both ways via a single connection, delivering speed and real-time capability on the web. WebSockets also allow servers to keep track of clients and push data to them as needed, which is not achievable using only HTTP. WebSockets are used in various scenarios where real-time communication is essential, such as:
Flutter extensively offers robust support for WebSockets with WebSocketIO class. However, it is crucial to stay aware of the fact that this package relies on ‘dart.io’ and ‘dart:html’, and due to this, we cannot compile for web and mobile applications simultaneously at the same time. To deal with this issue, the team at Dart has created the ‘web_socket_channel’ package, which compiles both libraries to run comfortably in cross-platform development.
Let us start by creating a new one. Firstly, ensure you have the latest Dart SDK installed. Open your terminal and run the following commands:
Let’s begin by examining the Dart server code, which is proficient in actively listening for WebSocket IO requests directed towards it, guaranteeing adept handling of such requests.
void main(Listargs) 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'); }, ); } }
Next, let’s incorporate some logic to transmit data from our server to the connected client. Specifically, we’ll dispatch prices for random cryptocurrency coins to the client for monitoring. These prices will be updated at one-second intervals, facilitating real-time testing of our client connection.
A dedicated function has been developed to generate random prices for five coins, ranging between 100 and 200, upon each invocation.
Proceeding further, add the logic to manage the WebSocket request and transmit the prices of cryptocurrency coins in response.
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( jsonEncode(initialPrices), ); // Set up a timer to update prices every second Timer.periodic( Duration(seconds: 1), (timer) { List > updatedPrices = generateRandomPrices(); webSocket.add( jsonEncode(updatedPrices), ); }, ); webSocket.listen( (data) { // You can add custom logic for handling client messages here print('Received data: $data'); }, onDone: () { print('Client disconnected'); }, ); }, );
We have also implemented a 3-second delay in the initial request to manage the loading behavior effectively.
To run the dart server project, run the following command in your terminal:
Hire Flutter Developers from us and start Today!
To initiate a new Flutter project, it’s imperative to have the most recent Flutter SDK installed. Navigate to your terminal and execute the subsequent commands:
To efficiently utilize websockets in Dart, we must integrate the web_socket_channel package into our project. Navigate to the ‘pubspec.yaml’ file located at the root of your project and include the following lines:
Don’t forget to run `flutter pub get` in your terminal to fetch and install the new dependencies.
Now that the project setup is complete, we will develop a straightforward application that establishes a connection to a WebSocket 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(), ), );
WebSocket URLs typically begin with “ws:” or “wss:”. We are ready to interact with incoming data now that we’ve successfully connected to a WebSocket. But have you considered how this data will be presented and updated each time new information arrives from the server?
To address this, we will leverage Flutter’s built-in StreamBuilder widget. This widget can refresh data whenever fresh information is detected within the data stream. WebSocket relies on such a data stream to facilitate bidirectional communication, which is crucial for real-time applications.
Now, building a StreamBuilder widget that receives the data from our websocket and displays the data
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) { Listbody = jsonDecode(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(), ); } }, ), ), ); } }
This simple app connects to a WebSocket with the help of the StreamBuilder widget and displays the information received from the server.
The full code repository is here:
https://github.com/yogesh-bacancy/flutter_web_sockets
With this, we can infer that building real-time apps with Flutter and WebSockets is a powerful solution to craft real-time features. By establishing bidirectional communication channels between clients and servers, your development team can create engaging, interactive experiences that meet the demands of today’s users. With robust support for websockets in both server-side Dart and Flutter, developers have the tools to build scalable, real-time applications across platforms. You can also contact a Flutter App Development Company that can help you develop real-time app communication features within your Flutter development project.
Flutter supports websocket communication on mobile (iOS, Android), web, and desktop platforms.
Yes! You can integrate websocket functionality alongside existing HTTP-based APIs in Flutter applications to facilitate real-time communication while leveraging traditional RESTful endpoints for other operations.
As with client-server communication, developers should implement appropriate security measures such as encryption (SSL/TLS) and authentication to protect sensitive data transmitted over websocket connections. Additionally, developers should be wary of potential vulnerabilities such as cross-site scripting (XSS) and cross-site request forgery (CSRF) when handling websocket messages on the client side.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.