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
Install
flutter pub add connectmq # Flutter
dart pub add connectmq # DartRequires Dart 3.8 or later. Android apps need the INTERNET permission and macOS apps the com.apple.security.network.client entitlement.
Publish and subscribe
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:
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
| Member | Content |
|---|---|
topic | The topic it was published to |
payload | The payload as a UTF-8 String |
bytes | The raw payload (Uint8List) |
json() | The payload decoded as JSON |
qos, retain | QoS level and retained flag |
received | Local 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
| Option | Default | Notes |
|---|---|---|
transport | tls (wss on the web) | MqttTransport.tls 8883, .wss 8084, .tcp 1883, .ws 8083 |
host | broker.connectmq.com | |
clientId | dart- + random | Set it to <issued client ID>_<suffix> |
username, password | none | From MQTT Connection Settings |
keepAlive | 60 s | |
timeout | 10 s | Connect timeout, also the QoS 1/2 acknowledgement timeout |
cleanSession | true |
Platforms and reconnecting
- Flutter web can only use WebSockets: the default there is
wss(port 8084).tcpandtlsthrow aConnectMQExceptionin the browser. - The package speaks MQTT 3.1.1.
- It does not reconnect automatically. When the connection drops, subscription streams emit a
ConnectMQExceptionand close, andclient.donecompletes. Listen todoneand callConnectMQClient.connect()again, for example when the app returns to the foreground.
Test from the command line
dart pub global activate connectmq
connectmq test # connect, publish, receive against the public test brokerThe 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/.