Flutter Mqtt Tutorial
Okay, let’s get to the point, for a detailed explanation you can visit the official mqtt website.
we add the mqtt package for flutter
here I will provide a tutorial on using mqtt in flutter. in this case I will use mqtt for my chat project to detect when our chat partner is typing.
in this case I will make the mqtt function support mobile and web.
Get Code September’s stories in your inbox
Join Medium for free to get updates from this writer.
we create the interface first. we name the file mqtt_client.dart
abstract class MqttService{
Future<void> connectMQTT({
required Function() onConnected,
required Function() onDisconnected,
required Function(String topic) onSubscribed,
required Function(Exception e) onError,
});
int publishMessage(
String topic,
MqttQos qualityOfService,
MqttClientPayloadBuilder data,
{bool retain = false});
void subscribe(String topic, MqttQos qosLevel, Function(String message) onMessage);
void mqttDisconnect();
}now we create the mqtt function for the mobile app part. we name the file mqtt_service_impl.dart
class MqttServiceImpl implements MqttService{
MqttServiceImpl(this.mqttServer, this.mqttServerIdentifier){
client = MqttServerClient(mqttServer, '');
}
final String mqttServer;
final String mqttServerIdentifier;
late MqttClient client;
@override
Future<void> connectMQTT({
required Function() onConnected,
required Function() onDisconnected,
required Function(String topic) onSubscribed,
required Function(Exception e) onError,
}) async {
client.logging(on: false);
client.setProtocolV311();
client.keepAlivePeriod = 20;
client.connectTimeoutPeriod = 2000;
client.onDisconnected = (){
debugPrint('Mosquitto OnDisconnected client callback - Client disconnection');
if (client.connectionStatus!.disconnectionOrigin == MqttDisconnectionOrigin.solicited) {
debugPrint('Mosquitto OnDisconnected callback is solicited, this is correct');
} else {
debugPrint('Mosquitto OnDisconnected callback is unsolicited or none, this is incorrect - exiting');
}
onDisconnected.call();
};
client.onConnected = () {
onConnected.call();
};
client.onSubscribed = (String topic){
onSubscribed.call(topic);
debugPrint('Mosquitto client Subscribed to Topic $topic');
};
final connMess = MqttConnectMessage()
.withClientIdentifier(mqttServerIdentifier)
.withWillTopic('willtopic')
.withWillMessage('My Will message')
.startClean()
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMess;
try {
await client.connect();
} on NoConnectionException catch (e) {
client.disconnect();
debugPrint('Mosquitto client exception - $e');
onError.call(e);
}
}
@override
int publishMessage(topic, qualityOfService, data, {bool retain = false}) {
return client.publishMessage(topic, qualityOfService, data.payload!);
}
@override
void subscribe(String topic, MqttQos qosLevel, Function(String message) onMessage) {
client.subscribe(topic, qosLevel);
client.updates?.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
final recMess = c![0].payload as MqttPublishMessage;
final pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
onMessage.call(pt);
debugPrint('Mosquitto Change notification:: topic is ${c[0].topic}, payload is $pt');
});
client.published?.listen((MqttPublishMessage message) {
debugPrint(
'Mosquitto Published message topic is '
'${message.variableHeader!.topicName}, '
'with Qos ${message.header!.qos}');
});
}
@override
void mqttDisconnect() {
client.disconnect();
}
}now for web support mqtt_web_service_impl.dart
class MqttServiceImpl implements MqttService{
MqttServiceImpl(this.mqttServer, this.mqttServerIdentifier){
mqttServer = 'ws://$mqttServer';
client = MqttBrowserClient(mqttServer, mqttServerIdentifier);
}
late String mqttServer;
final String mqttServerIdentifier;
late MqttClient client;
@override
Future<void> connectMQTT({
required Function() onConnected,
required Function() onDisconnected,
required Function(String topic) onSubscribed,
required Function(Exception e) onError,
}) async {
client.logging(on: false);
client.setProtocolV311();
client.keepAlivePeriod = 20;
client.connectTimeoutPeriod = 2000;
client.port = 8080;
client.websocketProtocols = MqttClientConstants.protocolsSingleDefault;
client.onDisconnected = (){
debugPrint('Mosquitto OnDisconnected client callback - Client disconnection');
if (client.connectionStatus!.disconnectionOrigin == MqttDisconnectionOrigin.solicited) {
debugPrint('Mosquitto OnDisconnected callback is solicited, this is correct');
} else {
debugPrint('Mosquitto OnDisconnected callback is unsolicited or none, this is incorrect - exiting');
}
onDisconnected.call();
};
client.onConnected = () {
onConnected.call();
};
client.onSubscribed = (String topic){
onSubscribed.call(topic);
debugPrint('Mosquitto client Subscribed to Topic $topic');
};
final connMess = MqttConnectMessage()
.withClientIdentifier(mqttServerIdentifier)
.withWillTopic('willTopic')
.withWillMessage('My Will message')
.startClean()
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMess;
try {
await client.connect();
} on NoConnectionException catch (e) {
client.disconnect();
debugPrint('Mosquitto client exception - $e');
onError.call(e);
}
}
@override
int publishMessage(topic, qualityOfService, data, {bool retain = false}) {
return client.publishMessage(topic, qualityOfService, data.payload!);
}
@override
void subscribe(String topic, MqttQos qosLevel, Function(String message) onMessage) {
client.subscribe(topic, qosLevel);
client.updates?.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
final recMess = c![0].payload as MqttPublishMessage;
final pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
onMessage.call(pt);
debugPrint('Mosquitto Change notification:: topic is ${c[0].topic}, payload is $pt');
});
client.published?.listen((MqttPublishMessage message) {
debugPrint(
'Mosquitto Published message topic is '
'${message.variableHeader!.topicName}, '
'with Qos ${message.header!.qos}');
});
}
@override
void mqttDisconnect() {
client.disconnect();
}
}const String mqttServer = 'test.mosquitto.org';so that we can use both mqtt mobile and web functions, here is the key
import 'package:mqtt_service_impl.dart'
if (dart.library.js) 'package:mqtt_web_service_impl.dart';
class TypingService{
final mqttService = MqttServiceImpl(mqttServer, mqttServerIdentifier);
Future<void> connectMQTT() async {
await mqttService.connectMQTT(
onConnected: () {
print('onConnected');
},
onDisconnected: () {
print('onDisconnected');
},
onError: (e) {
print('onError ${e.toString()}');
},
onSubscribed: (topic) {
print('onSubscribed ${topic}');
},
);
}
Future<void> publishMessage({required String message}) async {
final builder = MqttClientPayloadBuilder();
builder.addString(message);
mqttService.publishMessage(
'topic',
MqttQos.exactlyOnce, builder
);
}
@override
Future<void> subscribe() async {
mqttService.subscribe(
'topic'
MqttQos.atMostOnce,
(message) {
print(message);
},
);
}
}






