Playing with Flutter and WebSockets

Gino Busok Jr
4 min readAug 21, 2020

This story is about my first hand experience with Flutter. I don’t want to create a boring Hello World app so I created an app that is actually going to be useful at least for me. From the title, this app will connect to a WebSocket API. The app will be able to send a request and then print out the response.

A short backstory. I am a registered user of https://pro.coins.asia/. This is coins.ph digital currency exchange platform. It has all the features I need to trade some bitcoins but it has no mobile app (or there is?). So I decided to create one. I also wanted to learn a new tech so I chose Flutter. https://flutter.dev/

Before we proceed, you may want to download and read Coins Pro WebSocket API here https://pro.coins.asia/coins-pro-api/. We will be using GetProducts API because it does not require an authenticated call.

Assumptions

  1. You already installed Flutter. If not, check this link https://flutter.dev/docs/get-started/install
  2. You have installed and setup your android development environment.
  3. If you want to develop an iOS app, you need a mac and you need to install XCode.
  4. You have installed and setup an IDE of your choice. I am using VSCode.

Let’s create the app.

On a terminal run these commands

flutter create name_of_your_app
cd name_of_your_app
# Run your app
flutter run

If you setup your environment properly, your app should already run and you should see something like this:

Hurray! You successfully run a Flutter app. Click that Floating Button and see the counter increase.

Now open your app’s codes directory. Read this if you are also using VSCode https://flutter.dev/docs/development/tools/vs-code

Adding Dependency

Since we will be connecting to a WebSocket, we need to add a new dependency. For flutter, dependencies are being managed in pubsec.yaml file. Under dependencies, add web_socket_channel: ^1.1.0

Then run flutter pub get to get the new package. To learn more about flutter commands just run flutter -h

Time to do some coding

Open lib/main.dart This file is your app’s main Entry Point. We will only edit this file for this story, which might not be the best way. But hey, I am still new to this :).

Add 3 new imports

import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'dart:convert'; // We will need jsonEncode to send data

At the end of this file, create a new stateless widget. Google “Flutter Stateless vs Stateful” if you want to know more. If you are using VSCode, you can just type “st” and this should pop-up. Click “Flutter stateful widget”.

Type “Product” in the generated codes. And you should now have this code block. If you using a different IDE, just copy the codes below.

Now let’s update Product class. We will add a new property of type WebSocketChannel. We will initialize this property using the class’ constructor.

final WebSocketChannel channel; // New PropertyProduct({ @required this.channel}); // class Product constructor

Next we will be updating the build method of _ProductState. You can get more info for the build method here https://api.flutter.dev/flutter/widgets/State/build.html Basically build method is where the rendering of your App happens.

The class _ProductState is where we will send the request that will be handled by the API. Then it should send us a response. For this story, we will just print out the response of the WebSocket API.

We will use StreamBuilder class. From the documentation, this is a widget that builds itself based on the latest snapshot of interaction with a Stream. So if there is any new data from the Websocket API, our Product widget will rebuild itself to show that data. That is what line 11 will do.

Then we need to send data to the Websocket API. For now, we will do this inside _ProductState by overriding initState method (https://api.flutter.dev/flutter/widgets/State/initState.html). As an additional note, if you want to learn more about Stateful Widget, read this https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html It contains all the things you need to know about StatefulWidget.

Based on GetProductsdocumentation, our request should be this JSON string

{ "m":0, "i":0, "n":"GetProducts", "o":"{\"OMSId\": 1}" }

One way to do this in Flutter is to use a Map and then use jsonEncode to convert the Map to a JSON string. The code can be found below.

4) We created a new Map with key of type String and Dynamic value.

8) Property ‘o’ should also be a JSON string

9) Convert the map to JSON String

10) Send json string to the WebSocket API using sink.add method

At this point, Product widget is now complete.

We will now use our Product widget. Update build method of class MyApp. Change the home to

...
home: Product(channel: IOWebSocketChannel.connect('wss://api.coins.asia/WSGateway/')),
);
...

Here we are just initializing the Product widget by creating a new Websocket connection using IOWebSocketChannel.connect method (https://api.flutter.dev/flutter/web_socket_channel.io/IOWebSocketChannel/IOWebSocketChannel.connect.html)

And we are done. Try running the app flutter runIf everything is okay, your app should look like this

You can find the full code here

I will be updating this app hopefully soon. Stay tuned.

--

--