Using MQTT in the Flutter project

Project initialization

Create a project

Create a new project, can refer to the following links:

Install dependencies

Add dependencies into file pubspec.yaml

dependencies: 
mqtt_client: ^7.2.1
flutter pub get
import 'package:mqtt_client/mqtt_client.dart';

Use of MQTT

Connect to MQTT broker

This article will use the MQTT broker which is operated and maintained by EMQ X Cloud. EMQ X Cloud is the MQTT IoT cloud service platform released by EMQ, it provides the service for accessing MQTT 5.0 with all-in-one operation and maintenance and unique isolation environment.

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • Websocket Port: 8083

The example of connection

Future<MqttServerClient> connect() async {
MqttServerClient client =
MqttServerClient.withPort('broker.emqx.io', 'flutter_client', 1883);
client.logging(on: true);
client.onConnected = onConnected;
client.onDisconnected = onDisconnected;
client.onUnsubscribed = onUnsubscribed;
client.onSubscribed = onSubscribed;
client.onSubscribeFail = onSubscribeFail;
client.pongCallback = pong;

final connMessage = MqttConnectMessage()
.authenticateAs('username', 'password')
.keepAliveFor(60)
.withWillTopic('willtopic')
.withWillMessage('Will message')
.startClean()
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMessage;
try {
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
}

client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final MqttPublishMessage message = c[0].payload;
final payload =
MqttPublishPayload.bytesToStringAsString(message.payload.message);

print('Received message:$payload from topic: ${c[0].topic}>');
});

return client;
}

The description of callback method

// connection succeeded
void onConnected() {
print('Connected');
}

// unconnected
void onDisconnected() {
print('Disconnected');
}

// subscribe to topic succeeded
void onSubscribed(String topic) {
print('Subscribed topic: $topic');
}

// subscribe to topic failed
void onSubscribeFail(String topic) {
print('Failed to subscribe $topic');
}

// unsubscribe succeeded
void onUnsubscribed(String topic) {
print('Unsubscribed topic: $topic');
}

// PING response received
void pong() {
print('Ping response client callback invoked');
}

The example of certificate connection

/// Security context
SecurityContext context = new SecurityContext()
..useCertificateChain('path/to/my_cert.pem')
..usePrivateKey('path/to/my_key.pem', password: 'key_password')
..setClientAuthorities('path/to/client.crt', password: 'password');
client.secure = true;
client.securityContext = context;

Other MQTT operations

Subscribe to topic

client.subscribe("topic/test", MqttQos.atLeastOnce)

Publish message

const pubTopic = 'topic/test';
final builder = MqttClientPayloadBuilder();
builder.addString('Hello MQTT');
client.publishMessage(pubTopic, MqttQos.atLeastOnce, builder.payload);

Unsubscribe

client.unsubscribe('topic/test');

Disconnect

client.disconnect();

Test

We write a simple UI interface for this project and use MQTT 5.0 client tool — MQTT X to do the following tests:

  • connect
  • subscribe
  • publish
  • unsubscribe
  • disconnect

Summary

So far, we have finished that use Flutter to build MQTT applications in the Android platform, implemented the connection between the client and MQTT broker, subscribe, unsubscribe, publish and receive messages, etc.

--

--

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
EMQ Technologies

EMQ Technologies

EMQ is an open-source IoT data infrastructure software provider, delivering the world’s leading open-source MQTT message broker and stream processing database.