How to setup of a NodeJS WebSocket server and connect a Flutter app to build a simple chat app.
Were keeping the frontEnd to a as minimum as possible for learning purposes.
source code
First setup our NodeJS server. npm install ws
Flutter code for the main.dart. Were putting all of our code into one file to keep this simple.
import ‘package:flutter/material.dart’;
import ‘package:web_socket_channel/io.dart’;
void main() => runApp( MaterialApp(home: 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’);
var userInput; List messages = []; send2WebSocket() { channel.sink.add(userInput); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Column( children: <Widget>[ Expanded( child: StreamBuilder( stream: channel.stream, builder: (context, snapshot) {
// The data is being pulled from the websocket messages.add(snapshot.data); if (snapshot.hasData) { return ListView.builder( itemCount: messages.length, itemBuilder: (context, index) { return Text(messages[index] == null ? “” : ‘${messages[index]}’); }); } else { return Center( child: Text(‘No messages yet, start typing…’)); } }, ), ), FlatButton.icon( onPressed: () { send2WebSocket(); }, icon: Icon(Icons.send), label: Text(“send”)), TextField( onChanged: (value) { userInput = value; }, ), ], ), ); } }
Open up your pubspec.yaml file and add:web_socket_channel:^1.1.0
Now were ready to start flutter and our NodeJS webSocket server.
Start the server firstnode websocketServer.js
Then start flutter and run it on an emulator. I am using an iOS emulator. if you using android. The localhost needs to be set to (‘ws://10.0.2.2:8080’);
If you want to run both android and iOS emulators at the same time and connect to the server then you need to change to a remote server. I did just that. I created a free account with Oracle cloud then created a ubuntu linux instance. Its not the easiest thing to do if you not familiar with backend.
Maybe the flutter team will fix that bug in the next release and we could do this test locally.
Thanks for stopping by and I hope you all have a super wonderful day. Cheers 🍺