Real-Time Data in Flutter: Unlocking the Power of WebSockets
The Limitations of REST
In today’s fast-paced digital landscape, many applications require instant feedback to provide users with a seamless experience. Whether it’s a chat app that shows a person typing in real-time or a remote application that plots data directly from a hardware sensor, real-time data is essential. However, achieving this feat can be architecturally challenging, especially when relying on traditional RESTful APIs.
With REST, we must ping the server multiple times per minute to achieve near-instant feedback, which can overload the server and lead to architectural difficulties.
Enter WebSockets
Frameworks like Firebase rely on WebSockets, a powerful technology that enables two-way interactive communication between the user’s browser and a server. WebSockets allow us to send messages to a server and receive event-driven responses without having to poll the server for a reply. This real-time communication stream makes WebSockets ideal for stock-exchange apps, chat applications, IoT apps, and any other app that requires an incoming stream of data.
How WebSockets Work
A WebSocket consists of:
- A server that streams information
- A client in the application that is ready to receive the new stream of data
- A channel to communicate between the client and the server
- Messages sent between the client and the server
Unlike REST, with WebSockets, we don’t await a response from the server after sending a message. We can send one message and receive dozens of incoming messages from the server, making it a game-changer for real-time data applications.
Using WebSockets in Flutter
Fortunately, Flutter’s language, Dart, provides an out-of-box solution for dealing with WebSockets: the WebSocket class. However, when developing multi-platform apps, we must use the websocketchannel library to abstract the dart:io and dart:html logic.
Creating a Real-Time WebSocket Application
To demonstrate the power of WebSockets, we’ll create a simple Flutter app that displays real-time cryptocurrency prices using the CoinBase Pro API. We’ll follow three simple steps:
- Create a new client with WebSocketChannel and connect to a channel via the connect function
- Listen to incoming messages with the stream getter
- Use the sink getter to send messages to the server
import 'package:websocketchannel/websocketchannel.dart';
void main() {
final channel = WebSocketChannel.connect('wss://api.coinbase.com');
// Listen to incoming messages
channel.stream.listen((message) {
print('Received message: $message');
});
// Send a message to the server
channel.sink.add('Subscribe to ETH-EUR');
}
Displaying Real-Time Data in Flutter
Once we’ve created a WebSocket channel, we can create a Flutter app to showcase how we can use WebSockets. We’ll use the StreamBuilder widget to receive incoming messages from the server and react to them. Our app will:
- Show values for ETH-EUR
- Show values for BTC-EUR
- Close both channels if the user wants
import 'package:flutter/material.dart';
import 'package:websocketchannel/websocketchannel.dart';
class RealTimeDataApp extends StatefulWidget {
@override
_RealTimeDataAppState createState() => _RealTimeDataAppState();
}
class _RealTimeDataAppState extends State {
final channel = WebSocketChannel.connect('wss://api.coinbase.com');
String _ethEurValue = '';
String _btcEurValue = '';
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: channel.stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
// Update the values based on the incoming message
_ethEurValue = snapshot.data['ETH-EUR'];
_btcEurValue = snapshot.data['BTC-EUR'];
return Column(
children: [
Text('ETH-EUR: $_ethEurValue'),
Text('BTC-EUR: $_btcEurValue'),
],
);
} else {
return Center(child: CircularProgressIndicator());
}
},
);
}
}
Putting it all Together
By combining WebSockets with Flutter, we can create reactive applications that update in real-time. Whether you’re building a chat app, a stock-exchange app, or an IoT app, WebSockets can help you achieve instant feedback and provide a seamless user experience.
Have You Ever Needed to Display Real-Time Data?
We’d love to hear from you! Have you ever needed to display real-time data to users in your applications? If so, what did you use? Share your experiences with us! 😁