Skip to content

Dart / Flutter ​

The official connectmq package is a preconfigured mqtt_client wrapper for ConnectMQ. It runs on Android, iOS, macOS, Windows, Linux, the Dart VM and the web, and returns subscriptions as Dart streams.

How it connects ​

Dart / Flutter app connecting to ConnectMQ A Dart / Flutter app uses connectmq (pub.dev) · built on mqtt_client to connect to broker.connectmq.com over TLS 8883 · WSS 8084 on the web with a username, password and a client ID based on the issued client ID. The broker checks the client with the Broker API (credentials, client ID, ACL and plan limits) and delivers messages to the web console and other devices and services. Your codeEveryone else on the brokerConnectMQ CloudTLS 8883 · WSS 8084 on the webusername · password · client ID <ISSUED_ID>_<suffix>authDart / Flutter appconnectmq (pub.dev) · built on mqtt_clientawait client.publish('acme/…/tablet-01/telemetry', {'temperature': 21.5}, qos: 1);Android · iOS · desktop · web · subscriptions as Dart streamsMQTT brokerbroker.connectmq.comTLS 8883 · WSS 8084 /mqtt · MQTT 3.1.1 and 5Broker APICredentials · client IDACL · plan limitsWeb consoleapp.connectmq.com · live topics · alertsDevices & servicesESP32 · ConnectMQ Edge · back ends · appsMQTT messagesConnection check (credentials, client ID, ACL)

Install ​

bash
flutter pub add connectmq   # Flutter
dart pub add connectmq      # Dart

Requires Dart 3.8 or later. Android apps need the INTERNET permission and macOS apps the com.apple.security.network.client entitlement.

Publish and subscribe ​

dart
import 'package:connectmq/connectmq.dart';

Future<void> main() async {
  final client = await ConnectMQClient.connect(
    transport: MqttTransport.tls,                    // mqtts://broker.connectmq.com:8883 (wss on the web)
    clientId: 'connectmq_client_123456_flutter-app', // issued client ID + "_" + suffix
    username: 'cmq_xxxxxxxxxxxx',
    password: const String.fromEnvironment('CMQ_PASSWORD'),
  );

  final sub = client.subscribe('acme/istanbul/#', qos: 1);
  sub.listen((m) => print('${m.topic}: ${m.payload}'));
  await sub.ready; // the broker acknowledged the subscription

  // Maps are sent as JSON; with qos 1 the call completes when the broker acknowledges it
  await client.publish('acme/istanbul/assembly/line1/tablet-01/telemetry', {'temperature': 21.5}, qos: 1);
}

Pass the password at build time with flutter run --dart-define=CMQ_PASSWORD=... instead of writing it in the source.

Always set clientId

Without clientId the package uses a random dart-... ID, which your private broker refuses. Use your issued client ID plus a suffix, and give every installation its own suffix, for example a device ID stored on first launch (why).

connect() throws a ConnectMQException when the connection fails, for example on a wrong password.

Show live values in a widget ​

subscribe() returns a Stream, so it plugs straight into a StreamBuilder:

dart
import 'package:connectmq/connectmq.dart';
import 'package:flutter/material.dart';

class Temperature extends StatefulWidget {
  const Temperature({super.key, required this.client, required this.topic});

  final ConnectMQClient client;
  final String topic;

  @override
  State<Temperature> createState() => _TemperatureState();
}

class _TemperatureState extends State<Temperature> {
  // Create the stream once (not in build): it is single-subscription
  late final Stream<ConnectMQMessage> _messages = widget.client.subscribe(widget.topic);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<ConnectMQMessage>(
      stream: _messages,
      builder: (context, snapshot) {
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        if (!snapshot.hasData) return const CircularProgressIndicator();
        final data = snapshot.data!.json() as Map<String, dynamic>;
        return Text('${data['temperature']} °C');
      },
    );
  }
}

When the widget is disposed, the listener is cancelled and the topic is unsubscribed on the broker. Create one ConnectMQClient for the whole app (for example in your app state) and call close() when you no longer need it.

Messages ​

MemberContent
topicThe topic it was published to
payloadThe payload as a UTF-8 String
bytesThe raw payload (Uint8List)
json()The payload decoded as JSON
qos, retainQoS level and retained flag
receivedLocal receive time

Other useful calls: waitForMessage(filter, timeout: ...) for the next (or retained) message, clearRetained(topic) to delete a retained message, and unsubscribe(filter).

Options ​

OptionDefaultNotes
transporttls (wss on the web)MqttTransport.tls 8883, .wss 8084, .tcp 1883, .ws 8083
hostbroker.connectmq.com
clientIddart- + randomSet it to <issued client ID>_<suffix>
username, passwordnoneFrom MQTT Connection Settings
keepAlive60 s
timeout10 sConnect timeout, also the QoS 1/2 acknowledgement timeout
cleanSessiontrue

Platforms and reconnecting ​

  • Flutter web can only use WebSockets: the default there is wss (port 8084). tcp and tls throw a ConnectMQException in the browser.
  • The package speaks MQTT 3.1.1.
  • It does not reconnect automatically. When the connection drops, subscription streams emit a ConnectMQException and close, and client.done completes. Listen to done and call ConnectMQClient.connect() again, for example when the app returns to the foreground.

Test from the command line ​

bash
dart pub global activate connectmq
connectmq test        # connect, publish, receive against the public test broker

The public test broker needs no account, but anyone can read its topics: use it for experiments only, under a random prefix such as connectmq/demo/7f3a91/.

Fully managed MQTT broker for connected devices.