Create a real-time chat with pure Flutter and Dart
Flutter is getting more and relevant in the application environment. You can create mobile apps, web apps and desktop apps as well. One language to rule them all.
It’s natural to ask, whether you can write server-side application or backend in Dart too. And the answer is: yes!
The shelf ecosystem
Shelf is a concept of composing web server or parts of it. It is created, maintained and backed by the Dart team. You already use it in your daily Flutter work: The packages service pub.dev is written in Dart using shelf.
So we can all agree that this is battle tested by millions of users.
I have written the shelf_plus package. It comes with hot-reload preconfigured, as you would expect it from working with Flutter. Also the API is very easy to use:
The backend part
In order to set up a real-time chat service we need a backend service. As promised we use Dart with shelf and WebSocket as the communication technology. Unlike HTTP requests the WebSockets allow us to communicate bi-directional. There is no need to poll the server. The server can supply a message from client A to client B nearly instantly.
Here is an implementation using shelf_plus:
A chat application is a very simple use case. But you might use this pattern to create larger applications like real-time multiplayer games with Flutter.
WebSocketSession we can react on the lifecycle of a socket connection. The most important part is the
onMessage where you can implement your own communication protocol. For now we straight send strings (and display them as they are).
The Flutter part
Basically we need to connect to the server and listen to all incoming messages, memorize them. Here is a short API breakdown:
This is all we need to create a real-time multiplayer application like a chat. The rest is building a beautiful user interface with a form field, button and a auto-scrolling view with chat bubbles.
My take on this can be looked up here: flutter_chat/../main.dart
The whole backend dart project can be found here: flutter_websocket_chat.
In summary I wanted you to show how you can easily write backend services, especially real-time services, with the language you already know: Dart. And I demonstrated how neatly the WebSocket handling integrates into the code, thanks to Stream handling and packages giving us some level of abstraction.
If you are interested in WebSockets or server-side Dart use the sources I linked within the text.
I hope you enjoyed it. If so, leave some clapps. :-)
— Felix —