tencent cloud

Dart SDK
Last updated:2026-01-30 15:02:26
Dart SDK
Last updated: 2026-01-30 15:02:26

Feature Overview

The Dart/Flutter platform provides two main MQTT client libraries:

mqtt_client

The client library for the MQTT 3.1/3.1.1 protocol is compatible with Flutter, Dart VM, and Web platforms. It provides MqttServerClient and MqttBrowserClient for server-side and browser environments.

mqtt5_client

The client library specifically designed for the MQTT 5.0 protocol offers full support for MQTT 5.0 features, including enhanced authentication, message properties, topic aliases, and more. It also supports both server and browser environments.

Cloud Resource Preparation

Please refer to create a resource operation steps to complete cloud resource preparation.

Preparing the Environment

Select the Appropriate Client Library

Select the corresponding library based on the MQTT protocol version you need to use:
Use MQTT 3.1.1 (recommended for production environments).
dependencies:
mqtt_client: ^10.11.0

Use MQTT 5.0.
dependencies:
mqtt5_client: ^4.15.2

Then run:
flutter pub get
# or
dart pub get

Example Code

MQTT 5.0
MQTT 5.0 TLS
MQTT 3
MQTT 3 TLS

import 'dart:async';
import 'dart:convert';
import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';

Future<void> main() async {
// Obtain the access point from the MQTT console
final server = 'mqtt-xxx.mqtt.tencenttdmq.com';
final port = 1883;

// A valid Client Identifier contains digits 0-9, lowercase letters a-z, and uppercase letters A-Z, with a total length of 1-23 characters
final clientId = 'QuickStartMqtt5';

// On the console --> Authentication Tab page, create an account and copy the username and password
final username = 'YOUR_USERNAME';
final password = 'YOUR_PASSWORD';

// Confirm that the first-level topic "home" has been created in the MQTT console
final pubTopic = 'home/test';
final topicFilters = ['home/test', 'home/#', 'home/+'];
final qos = [MqttQos.atLeastOnce, MqttQos.atLeastOnce, MqttQos.atLeastOnce];

final total = 16;

final client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true);
client.keepAlivePeriod = 60;
client.autoReconnect = true;

// Set the connection message
final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId)
.authenticateAs(username, password)
.startClean();
client.connectionMessage = connMessage;

// Connection callback
client.onConnected = () {
print('Connected to $server');
// Subscribe
for (var i = 0; i < topicFilters.length; i++) {
client.subscribe(topicFilters[i], qos[i]);
print('Subscribed to topic ${topicFilters[i]} with QoS=${qos[i].index}');
}
};

client.onDisconnected = () {
print('Disconnected');
};

client.onAutoReconnect = () {
print('Auto reconnecting...');
};

client.onAutoReconnected = () {
print('Auto reconnected');
};

try {
print('Connecting to MQTT broker...');
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
return;
}

if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('MQTT client connected');

// Subscribe message callback
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final recMessage = c[0].payload as MqttPublishMessage;
final topic = c[0].topic;
final payload = recMessage.payload.message;
final content = payload != null ? utf8.decode(payload.toList()) : '';
print('Message arrived, topic=$topic, QoS=${recMessage.payload.header!.qos.index} content=[$content]');
});

// Publish a message
for (var i = 0; i < total; i++) {
final builder = MqttPayloadBuilder();
builder.addString('Hello MQTT 5.0 - $i');
print('Prepare to publish message $i');
client.publishMessage(pubTopic, qos[0], builder.payload!);
print('Published message $i');
await Future.delayed(Duration(seconds: 3));
}

await Future.delayed(Duration(seconds: 3));
client.disconnect();
} else {
print('Connection failed - status is ${client.connectionStatus}');
client.disconnect();
}
}


import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';

Future<void> main() async {
// Obtain the access point from the MQTT console
final server = 'mqtt-xxx.mqtt.tencenttdmq.com';
final port = 8883;

// A valid Client Identifier contains digits 0-9, lowercase letters a-z, and uppercase letters A-Z, with a total length of 1-23 characters
final clientId = 'QuickStartMqtt5Tls';

// On the console --> Authentication Tab page, create an account and copy the username and password
final username = 'YOUR_USERNAME';
final password = 'YOUR_PASSWORD';

// Confirm that the first-level topic "home" has been created in the MQTT console
final pubTopic = 'home/test';
final topicFilters = ['home/test', 'home/#', 'home/+'];
final qos = [MqttQos.atLeastOnce, MqttQos.atLeastOnce, MqttQos.atLeastOnce];

final total = 16;

final client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true);
client.keepAlivePeriod = 60;
client.autoReconnect = true;
client.secure = true;

// Configure TLS/SSL
SecurityContext context = SecurityContext.defaultContext;
client.securityContext = context;
client.onBadCertificate = (dynamic certificate) => true; // Used in development environments; in production environments, certificates should be verified

// Set the connection message
final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId)
.authenticateAs(username, password)
.startClean();
client.connectionMessage = connMessage;

// Connection callback
client.onConnected = () {
print('Connected to $server');
// Subscribe
for (var i = 0; i < topicFilters.length; i++) {
client.subscribe(topicFilters[i], qos[i]);
print('Subscribed to topic ${topicFilters[i]} with QoS=${qos[i].index}');
}
};

client.onDisconnected = () {
print('Disconnected');
};

client.onAutoReconnect = () {
print('Auto reconnecting...');
};

client.onAutoReconnected = () {
print('Auto reconnected');
};

try {
print('Connecting to MQTT broker...');
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
return;
}

if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('MQTT client connected');

// Subscribe message callback
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final recMessage = c[0].payload as MqttPublishMessage;
final topic = c[0].topic;
final payload = recMessage.payload.message;
final content = payload != null ? utf8.decode(payload.toList()) : '';
print('Message arrived, topic=$topic, QoS=${recMessage.payload.header!.qos.index} content=[$content]');
});

// Publish a message
for (var i = 0; i < total; i++) {
final builder = MqttPayloadBuilder();
builder.addString('Hello MQTT 5.0 TLS - $i');
print('Prepare to publish message $i');
client.publishMessage(pubTopic, qos[0], builder.payload!);
print('Published message $i');
await Future.delayed(Duration(seconds: 3));
}

await Future.delayed(Duration(seconds: 3));
client.disconnect();
} else {
print('Connection failed - status is ${client.connectionStatus}');
client.disconnect();
}
}


import 'dart:async';
import 'dart:convert';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

Future<void> main() async {
// Obtain the access point from the MQTT console:
// Users who have implemented VPC network connectivity via Private Link use the private network access point;
// For users accessing over the public network, ensure the public network security policy permits access, and the machine running the program has public network connectivity;
final server = 'mqtt-xxx.mqtt.tencenttdmq.com';
final port = 1883;

// A valid Client Identifier contains digits 0-9, lowercase letters a-z, and uppercase letters A-Z, with a total length of 1-23 characters
// Refer to https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059
final clientId = 'QuickStart';

// On the console --> Authentication Tab page, create an account and copy the username and password
final username = 'YOUR_USERNAME';
final password = 'YOUR_PASSWORD';

// Confirm that the first-level topic "home" has been created in the MQTT console
final pubTopic = 'home/test';
final topicFilters = ['home/test', 'home/#', 'home/+'];
final qos = [MqttQos.atLeastOnce, MqttQos.atLeastOnce, MqttQos.atLeastOnce];

final total = 16;

final client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true);
client.setProtocolV311(); // Use the MQTT 3.1.1 protocol
client.keepAlivePeriod = 60;
client.autoReconnect = true;
client.connectTimeoutPeriod = 3000;

// Set the connection message
final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId)
.authenticateAs(username, password)
.startClean()
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMessage;

// Connection callback
client.onConnected = () {
print('Connected to $server');
// Subscribe
for (var i = 0; i < topicFilters.length; i++) {
client.subscribe(topicFilters[i], qos[i]);
print('Subscribed to topic ${topicFilters[i]} with QoS=${qos[i].index}');
}
};

client.onDisconnected = () {
print('Disconnected');
};

client.onAutoReconnect = () {
print('Auto reconnecting...');
};

client.onAutoReconnected = () {
print('Auto reconnected');
};

try {
print('Connecting to MQTT broker...');
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
return;
}

if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('MQTT client connected');

// Subscribe message callback
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final recMessage = c[0].payload as MqttPublishMessage;
final topic = c[0].topic;
final payload = recMessage.payload.message;
final content = payload != null ? utf8.decode(payload.toList()) : '';
print('Message arrived, topic=$topic, QoS=${recMessage.payload.header!.qos.index} content=[$content]');
});

// Publish a message
for (var i = 0; i < total; i++) {
final builder = MqttClientPayloadBuilder();
builder.addString('Hello MQTT $i');
print('Prepare to publish message $i');
client.publishMessage(pubTopic, MqttQos.atLeastOnce, builder.payload!);
print('Published message $i');
await Future.delayed(Duration(seconds: 3));
}

await Future.delayed(Duration(seconds: 3));
client.disconnect();
} else {
print('Connection failed - status is ${client.connectionStatus}');
client.disconnect();
}
}




import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

Future<void> main() async {
// Obtain the access point from the MQTT console:
// Users who have implemented VPC network connectivity via Private Link use the private network access point;
// For users accessing over the public network, ensure the public network security policy permits access, and the machine running the program has public network connectivity;
final server = 'mqtt-xxx.mqtt.tencenttdmq.com';
final port = 8883;

// A valid Client Identifier contains digits 0-9, lowercase letters a-z, and uppercase letters A-Z, with a total length of 1-23 characters
// Refer to https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901059
final clientId = 'ClientQuickStartTls';

// On the console --> Authentication Tab page, create an account and copy the username and password
final username = 'YOUR_USERNAME';
final password = 'YOUR_PASSWORD';

// Confirm that the first-level topic "home" has been created in the MQTT console
final pubTopic = 'home/test';
final topicFilters = ['home/test', 'home/#', 'home/+'];
final qos = [MqttQos.atLeastOnce, MqttQos.atLeastOnce, MqttQos.atLeastOnce];

final total = 16;

final client = MqttServerClient.withPort(server, clientId, port);
client.logging(on: true);
client.setProtocolV311(); // Use the MQTT 3.1.1 protocol
client.keepAlivePeriod = 60;
client.autoReconnect = true;
client.connectTimeoutPeriod = 3000;
client.secure = true;

// Configure TLS/SSL
SecurityContext context = SecurityContext.defaultContext;
client.securityContext = context;
client.onBadCertificate = (dynamic certificate) => true; // Used in development environments; in production environments, certificates should be verified

// Set the connection message
final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId)
.authenticateAs(username, password)
.startClean()
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMessage;

// Connection callback
client.onConnected = () {
print('Connected to $server');
// Subscribe
for (var i = 0; i < topicFilters.length; i++) {
client.subscribe(topicFilters[i], qos[i]);
print('Subscribed to topic ${topicFilters[i]} with QoS=${qos[i].index}');
}
};

client.onDisconnected = () {
print('Disconnected');
};

client.onAutoReconnect = () {
print('Auto reconnecting...');
};

client.onAutoReconnected = () {
print('Auto reconnected');
};

try {
print('Connecting to MQTT broker...');
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
return;
}

if (client.connectionStatus!.state == MqttConnectionState.connected) {
print('MQTT client connected');

// Subscribe message callback
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final recMessage = c[0].payload as MqttPublishMessage;
final topic = c[0].topic;
final payload = recMessage.payload.message;
final content = payload != null ? utf8.decode(payload.toList()) : '';
print('Message arrived, topic=$topic, QoS=${recMessage.payload.header!.qos.index} content=[$content]');
});

// Publish a message
for (var i = 0; i < total; i++) {
final builder = MqttClientPayloadBuilder();
builder.addString('Hello MQTT $i');
print('Prepare to publish message $i');
client.publishMessage(pubTopic, MqttQos.atLeastOnce, builder.payload!);
print('Published message $i');
await Future.delayed(Duration(seconds: 3));
}

await Future.delayed(Duration(seconds: 3));
client.disconnect();
} else {
print('Connection failed - status is ${client.connectionStatus}');
client.disconnect();
}
}



Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback