A Flutter guide to MQTT Protocol

Pedro Ganem
2 min readOct 28, 2020

Introduction

A few months ago, I started developing a Flutter App that controls an IoT device. During the learning process, I found several guides about widgets and UI in general. But when it came time to communicate the application with the MQTT broker and display data from it on the screen, I had a really hard time finding guides for it. So, what I’m going to try here is to write down what I wanted to find back there.

First things first!

After creating your Flutter project, open your pubspec.yaml file and add the mqtt_client package. Like this:

After that, create a new .dart file so we can start working on our setup.

Broker class setup

Create a new .dart file, import MqttClient, MqttServerClient and create a class for your broker setup.
The next step is to make your class a singleton, wich is a software design pattern that restricts the instantiation of a class to one “single” instance. This is useful when exactly one object is needed to coordinate actions across the system. Once you start learning about MQTT you’ll notice how important this is. Here’s how I’ve done it.

Now, lets create our class variables.

StreamSubscription will help us later!

After that, lets create our broker setup/connection and actions functions.

If you want to test the connection before we go further the app, just comment line 28 and remove "Function function" from line 1. But keep in mind that we'll need those to Stream the data received to our widgets!

We can subscribe and publish to topics by using:

//Subscribe to topic
client.subscribe(topic, qosLevel);
//Publish to topic
final builder = MqttClientPayloadBuilder(); builder.addString('your message');
client.publishMessage(topic, qosLevel, builder.payload);

Now, lets get back to the main.dart file and start coding our test app.
I build this simple app, wich will display data from the broker in real time.

Notice that the onMessage will be passed on the brokerSetup function, that means our StreamSubscription subscription will notificate when a new message arrives. By doing this, the application will know exactly when it's time to update the data on the screen. Awesome!
Let's take a look at the app:

And there you have it!

I hope I managed to help you in some way. Feel free to send me any questions or feedbacks. Stay safe and happy coding!

pedrocastilho.ganemg@gmail.com

--

--