mqtt_client 2.0.0

  • Example
  • Installing
  • Versions
  • 41


Build Status

A server side MQTT client for Dart.

The client is an MQTT v3(3.1 and 3.1.1) implementation supporting subscription/publishing at all QOS levels, keep alive and synchronous connection. The client is designed to take as much MQTT protocol work off the user as possible, connection protocol is handled automatically as are the message exchanges needed to support the different QOS levels and the keep alive mechanism. This allows the user to concentrate on publishing/subscribing and not the details of MQTT itself.

An example of usage can be found in the examples directory, this example is runnable. An example is also provided showing how to use the client to connect to the mqtt-bridge of Google's IoT-Core suite. This demonstrates how to use secure connections and switch MQTT protocols. The test directory also contains standalone runnable scripts for subscription and publishing.

The client supports both normal and secure TCP connections and server side websocket connections.

The code is a port from the C# nMQTT client library to Dart.


Issue 23, all subscriptions are now on one client level observable, not on seperate ones per subscription, this change is NOT backwards compatible


Issue 22, don't disconnect if we have no connection established


Issue 19, multitopic subscriptions + other more minor updates, API changed on this version.


Pull request 14, Making library more compliant to work with VerneMQ - explicit setting of will qos.


Issue 10, add library prefix for observable


Issue 10, update Observable version to 'any'


Add the payload builder utility.


Update Observable version


Remove eventable and its dependency on mirrors, replace with event_bus, issue 10


Fixes for issue 8, pub suggestions fixed.


Fixes for issues 5 and 6


Fixes for issues 3 and 4


Add secure sockets, server side only Add ability to select the MQTT protocol between 3.1 and 3.1.1 A few code and test tidy ups Tested to work with iot-core MQTT bridge


Add websockets as an alternative network connection server side only


Fix unit tests on Travis


Initial release


 * Package : mqtt_client
 * Author : S. Hamblett <>
 * Date   : 31/05/2017
 * Copyright :  S.Hamblett

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

/// An annotated simple subscribe/publish usage example for mqtt_client. Please read in with reference
/// to the MQTT specification. The example is runnable, also refer to test/mqtt_client_broker_test...dart
/// files for separate subscribe/publish tests.
Future<int> main() async {
  /// First create a client, the client is constructed with a broker name, client identifier
  /// and port if needed. The client identifier (short ClientId) is an identifier of each MQTT
  /// client connecting to a MQTT broker. As the word identifier already suggests, it should be unique per broker.
  /// The broker uses it for identifying the client and the current state of the client. If you don’t need a state
  /// to be hold by the broker, in MQTT 3.1.1 you can set an empty ClientId, which results in a connection without any state.
  /// A condition is that clean session connect flag is true, otherwise the connection will be rejected.
  /// The client identifier can be a maximum length of 23 characters. If a port is not specified the standard port
  /// of 1883 is used.
  /// If you want to use websockets rather than TCPO see below.
  final MqttClient client = new MqttClient("", "");

  /// A websocket URL must start with ws:// or Dart will throw an exception, consult your websocket MQTT broker
  /// for details.
  /// To use websockets add the following lines -:
  /// client.useWebSocket = true;
  /// client.port = 80;  ( or whatever your WS port is)

  /// Set logging on if needed, defaults to off

  /// If you intend to use a keep alive value in your connect message that is not the default(60s)
  /// you must set it here
  client.keepAlivePeriod = 30;

  /// Add the unsolicited disconnection callback
  client.onDisconnected = onDisconnected;

  /// Create a connection message to use or use the default one. The default one sets the
  /// client identifier, any supplied username/password, the default keepalive interval(60s)
  /// and clean session, an example of a specific one below.
  final MqttConnectMessage connMess = new MqttConnectMessage()
      .keepAliveFor(30) // Must agree with the keep alive set above or not set
      .withWillTopic("willtopic") // If you set this you must set a will message
      .withWillMessage("My Will message")
  print("EXAMPLE::Mosquitto client connecting....");
  client.connectionMessage = connMess;

  /// Connect the client, any errors here are communicated by raising of the appropriate exception. Note
  /// in some circumstances the broker will just disconnect us, see the spec about this, we however eill
  /// never send malformed messages.
  try {
    await client.connect();
  } catch (Exception) {
    /// Error handling.....

  /// Check we are connected
  if (client.connectionState == ConnectionState.connected) {
    print("EXAMPLE::Mosquitto client connected");
  } else {
        "EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, state is ${client

  /// Ok, lets try a subscription
  final String topic = "test/hw"; // Not a wildcard topic
  client.subscribe(topic, MqttQos.exactlyOnce);

  /// Our known topic to publish to
  final String pubTopic = "Dart/Mqtt_client/testtopic";

  /// Subscribe to it
  client.subscribe(pubTopic, MqttQos.exactlyOnce);

  /// The client has a change notifier object(see the Observable class) which we then listen to to get
  /// notifications of published updates to each subscribed topic.
  client.updates.listen((List<MqttReceivedMessage> c) {
    final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;
    final String pt =

    /// The above may seem a little convoluted for users only interested in the
    /// payload, some users however may be interested in the received publish message,
    /// lets not constrain ourselves yet until the package has been in the wild
    /// for a while.
    /// The payload is a byte buffer, this will be specific to the topic
    print("EXAMPLE::Change notification:: topic is <${c[0]
        .topic}>, payload is <-- ${pt} -->");

  /// Sleep to read the log.....
  await MqttUtilities.asyncSleep(5);

  /// Lets publish to our topic, use a high QOS

  // Use the payload builder rather than a raw buffer
  print("EXAMPLE::Publishing our topic");
  final MqttClientPayloadBuilder builder = new MqttClientPayloadBuilder();
  builder.addString("Hello from mqtt_client");
  client.publishMessage(pubTopic, MqttQos.exactlyOnce, builder.payload);

  /// Ok, we will now sleep a while, in this gap you will see ping request/response
  /// messages being exchanged by the keep alive mechanism.
  await MqttUtilities.asyncSleep(120);

  /// Finally, unsubscribe and exit gracefully

  /// Wait for the unsubscribe message from the broker if you wish.
  await MqttUtilities.asyncSleep(2);
  return 0;

/// The unsolicited disconnect callback
void onDisconnected() {
  print("OnDisconnected client callback - Client disconnection");

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  mqtt_client: ^2.0.0

2. Install it

You can install packages from the command line:

with pub:

$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:mqtt_client/mqtt_client.dart';
Version Uploaded Documentation Archive
2.0.0 Jul 18, 2018 Go to the documentation of mqtt_client 2.0.0 Download mqtt_client 2.0.0 archive
1.9.1 Jul 11, 2018 Go to the documentation of mqtt_client 1.9.1 Download mqtt_client 1.9.1 archive
1.9.0 Jul 2, 2018 Go to the documentation of mqtt_client 1.9.0 Download mqtt_client 1.9.0 archive
1.8.0 Jun 20, 2018 Go to the documentation of mqtt_client 1.8.0 Download mqtt_client 1.8.0 archive
1.7.2 May 27, 2018 Go to the documentation of mqtt_client 1.7.2 Download mqtt_client 1.7.2 archive
1.7.1 Apr 30, 2018 Go to the documentation of mqtt_client 1.7.1 Download mqtt_client 1.7.1 archive
1.7.0 Apr 20, 2018 Go to the documentation of mqtt_client 1.7.0 Download mqtt_client 1.7.0 archive
1.6.1 Apr 18, 2018 Go to the documentation of mqtt_client 1.6.1 Download mqtt_client 1.6.1 archive
1.6.0 Mar 22, 2018 Go to the documentation of mqtt_client 1.6.0 Download mqtt_client 1.6.0 archive
1.5.0 Feb 15, 2018 Go to the documentation of mqtt_client 1.5.0 Download mqtt_client 1.5.0 archive

All 15 versions...

Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0.

Issues and suggestions

Support Dart 2 in pubspec.yaml.

The SDK constraint in pubspec.yaml doesn't allow the Dart 2.0.0 release. For information about upgrading it to be Dart 2 compatible, please see


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <2.0.0