mqtt_client 5.1.0

  • Example
  • Installing
  • Versions
  • 93


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.

Examples of usage can be found in the examples directory. 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 secure(wss) and non-secure(ws) websocket connections.

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


Issues 54, 55 and 56


Roll up release for issues 48, 49, 50, 52 and 53, warning - breaking API change for connection state and security context in secure mode hence the major version bump.


Issue 45, better connection fail reporting, update linter, note breaking API change for turning logging on/off




Issue 40, disconnected clients




Issue 26, example code for flutter


Issue 38 QOS1 + 2 protocol handling bugs, Issue 34 Flutter buffers


Issue 38 QOS1 + 2 protocol handling bugs


Issue 37 onSubscribed and OnUnsubscribed callbacks


Issues 32 bug fix


Issues 32 and 35


Issues 27 and 29, pull request 30


Update to Dart 2, major version bump only to create a clean break from Dart 1


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 TCP see below.
  final MqttClient client = MqttClient('', '');

  /// A websocket URL must start with ws:// or wss:// 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)
  /// Note do not set the secure flag if you are using wss, the secure flags is for TCP sockets only.

  /// Set logging on if needed, defaults to off
  client.logging(on: false);

  /// 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 = 20;

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

  /// Add the successful connection callback
  client.onConnected = onConnected;

  /// Add a subscribed callback, there is also an unsubscribed callback if you need it.
  /// You can add these before connection or change them dynamically after connection if
  /// you wish.
  client.onSubscribed = onSubscribed;

  /// 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 = MqttConnectMessage()
      .keepAliveFor(20) // 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')
      .startClean() // Non persistent session for testing
  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();
  } on Exception catch (e) {
    print('EXAMPLE::client exception - $e');

  /// Check we are connected
  if (client.connectionStatus.state == MqttConnectionState.connected) {
    print('EXAMPLE::Mosquitto client connected');
  } else {
    /// Use status here rather than state if you also want the broker return code.
        'EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, status is ${client.connectionStatus}');

  /// Ok, lets try a subscription
  const String topic = 'test/lol'; // Not a wildcard topic
  client.subscribe(topic, MqttQos.atMostOnce);

  /// 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<MqttMessage>> c) {
    final MqttPublishMessage recMess = c[0].payload;
    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
        'EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');

  /// Lets publish to our topic
  // Use the payload builder rather than a raw buffer
  print('EXAMPLE::Publishing our topic');

  /// Our known topic to publish to
  const String pubTopic = 'Dart/Mqtt_client/testtopic';
  final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
  builder.addString('Hello from mqtt_client');

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

  /// Publish it
  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 subscribed callback
void onSubscribed(String topic) {
  print('EXAMPLE::Subscription confirmed for topic $topic');

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

/// The successful connect callback
void onConnected() {
      'EXAMPLE::OnConnected client callback - Client connection was sucessful');

Use this package as a library

1. Depend on it

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

  mqtt_client: ^5.1.0

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter packages get

Alternatively, your editor might support pub get or flutter packages 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
5.1.0 Dec 2, 2018 Go to the documentation of mqtt_client 5.1.0 Download mqtt_client 5.1.0 archive
5.0.0 Nov 26, 2018 Go to the documentation of mqtt_client 5.0.0 Download mqtt_client 5.0.0 archive
4.0.0 Nov 18, 2018 Go to the documentation of mqtt_client 4.0.0 Download mqtt_client 4.0.0 archive
3.3.6 Oct 21, 2018 Go to the documentation of mqtt_client 3.3.6 Download mqtt_client 3.3.6 archive
3.3.5 Oct 21, 2018 Go to the documentation of mqtt_client 3.3.5 Download mqtt_client 3.3.5 archive
3.3.4 Oct 6, 2018 Go to the documentation of mqtt_client 3.3.4 Download mqtt_client 3.3.4 archive
3.3.3 Oct 6, 2018 Go to the documentation of mqtt_client 3.3.3 Download mqtt_client 3.3.3 archive
3.3.2 Sep 28, 2018 Go to the documentation of mqtt_client 3.3.2 Download mqtt_client 3.3.2 archive
3.3.1 Sep 24, 2018 Go to the documentation of mqtt_client 3.3.1 Download mqtt_client 3.3.1 archive
3.3.0 Sep 23, 2018 Go to the documentation of mqtt_client 3.3.0 Download mqtt_client 3.3.0 archive

All 29 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.

We analyzed this package on Dec 5, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.7


Detected platforms: Flutter, other

Primary library: package:mqtt_client/mqtt_client.dart with components: io.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev <3.0.0
event_bus ^1.0.1 1.0.1
meta ^1.0.4 1.1.6
path ^1.6.2 1.6.2
typed_data ^1.1.6 1.1.6
Dev dependencies
coverage ^0.12.2
dart_style ^1.1.3
mockito ^3.0.0
test ^1.3.0