Connecting Flutter to NodeJS WebSocket.

Description: Were connecting Flutter to a NodeJS WebSocket server. We use nodeJS because its free and open source. Firebase costs way too much money.

After searching for google for Flutter WebSocket Node.js examples. I found almost nothing. So thats why I am writing this tutorial.

Source code repo: Flutter_Nodejs_WebSocket

What our final product will look like

I know its ugly but its functional.

VS Code: create a new Flutter project
MacOS :Cmd+Shift+P
Windows: Ctrl+Shift+P

Create your WebSocket server file inside our flutter project.

We need to install the WebSocket npm package.
npm init
npm install ws
ws is the best WebSocket library for node.js with over 20 million downloads. So make sure you install that one and not some other one.

This is all we need for the Node.js WebSocket server.

const WebSocket = require(“ws”);
// start the server and specify the port number
const port = 8080;
const wss = new WebSocket.Server({ port: port }); console.log(`[WebSocket] Starting WebSocket server on localhost:${port}`);
wss.on(“connection”, (ws, request) => { const clientIp = request.connection.remoteAddress;
console.log(`[WebSocket] Client with IP ${clientIp} has connected`); ws.send(“Thanks for connecting to this nodejs websocket server”);
// Broadcast aka send messages to all connected clients ws.on(“message”, (message) => { wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(message); } }); console.log(`[WebSocket] Message ${message} was received`); }); });

Now setup flutter. Where just going to use the main.dart file for all the code.

import ‘package:flutter/material.dart’;
import ‘package:web_socket_channel/io.dart’;
void main() => runApp(MyApp());
class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); }
class _MyAppState extends State<MyApp> {
// Localhost for android — 10.0.2.2
// Localhost for iOS — 127.0.0.1
final IOWebSocketChannel channel = IOWebSocketChannel.connect(‘ws://127.0.0.1:8080’);
@override Widget build(BuildContext context) {
return MaterialApp( home: StreamBuilder(
stream: channel.stream, builder: (context, snapshot) {
if (snapshot.hasError) return Text(‘Error: ${snapshot.error}’);
switch (snapshot.connectionState) { case ConnectionState.none: return Text(‘No connection’); case ConnectionState.waiting: return Text(‘Connected’); case ConnectionState.active: return Text(‘${snapshot.data}’); case ConnectionState.done: return Text(‘${snapshot.data} (closed)’); } return null; // unreachable }, ), ); } }

In your pubspec.yaml file add.
web_socket_channel: ^1.1.0

Make sure you save. MacOS cmd + S

The moment of truth.

Now run the server
node websocketServer.js

Start a Android or iOS emulator

Depending on Android or iOS you need to change the connection. I am using the iOS emulator so I am sticking with ws://127.0.0.1:8080

if Android emulator: connect(ws://10.0.2.2:8080)
if iOS emulator: connect(ws://127.0.0.1:8080)

The Result:

We setup the connection between Flutter and NodeJS WebSocket server.

So this is the end of the tutorial for now. I hope you have an absolutely wonderful day. Cheers .🍺

--

--

--

“Genius” is 1% inspiration and 99% perspiration. Accordingly, a ‘genius’ is often merely a talented person who has done all of his homework — T.E.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

9 Forms of Coupling in Software Architecture

“If you want a raise, learn Python”

Starting Open-Sourcing

Making of Vidhya.io

Building Enhanced Security into Our Container Platform

Singleton Design Pattern in C#

Investor Spotlight — Faculty Group

SQL Notes: Swap Salary

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kafka

Kafka

“Genius” is 1% inspiration and 99% perspiration. Accordingly, a ‘genius’ is often merely a talented person who has done all of his homework — T.E.

More from Medium

A tour with Dart syntax — Dart programming — Part 2

Data Structures and Algorithms in Dart

Flutter gallery: import show

Custom Option Selection Widget — Flutter.