The Flutter is a cross-platform, high fidelity, and high performance mobile application development framework developed by Google. Dart allows developers to develop apps, a set of code that runs on both iOS and Android. Flutter provides a rich set of components, interfaces, and developers can quickly add native extensions to Flutter. Flutter also uses the Native engine to render the view, which certainly provides a good user experience.

MQTT is a lightweight Internet of Things messaging protocol based on the publish/subscribe model, which can achieve stable transmission over severely limited hardware devices and low-bandwidth, high-latency networks. It is easy to implement, support QoS, small message and other characteristics, occupy half of the Internet of things protocol.

This article describes how to use MQTT in the Flutter project to enable the client to connect to the MQTT server, subscribe, unsubscribe, send and receive messages, and more.

Project initialization

New project

To create a new project, see the following link:

  • Set up an editor
  • Android Studio and IntelliJ

Install dependencies

Add dependencies to the pubspec.yaml file

dependencies: 
  mqtt_client: ^ 7.2.1
Copy the code

Install dependencies:

flutter pub get
Copy the code

The import

import 'package:mqtt_client/mqtt_client.dart';
Copy the code

The use of MQTT

Connect to the MQTT server

This article will use the free public MQTT server provided by EMQ X, which is built on EMQ X’s MQTT iot cloud platform. The server information is as follows:

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • Websocket Port: 8083

Connection sample code

Future<MqttServerClient> connect() async {
  MqttServerClient client =
      MqttServerClient.withPort('broker.emqx.io'.'flutter_client'.1883);
  client.logging(on: true);
  client.onConnected = onConnected;
  client.onDisconnected = onDisconnected;
  client.onUnsubscribed = onUnsubscribed;
  client.onSubscribed = onSubscribed;
  client.onSubscribeFail = onSubscribeFail;
  client.pongCallback = pong;

  final connMessage = MqttConnectMessage()
      .authenticateAs('username'.'password')
      .keepAliveFor(60)
      .withWillTopic('willtopic')
      .withWillMessage('Will message')
      .startClean()
      .withWillQos(MqttQos.atLeastOnce);
  client.connectionMessage = connMessage;
  try {
    await client.connect();
  } catch (e) {
    print('Exception: $e');
    client.disconnect();
  }

  client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
    final MqttPublishMessage message = c[0].payload;
    final payload =
    MqttPublishPayload.bytesToStringAsString(message.payload.message);

    print('Received message:$payload from topic: ${c[0].topic}> ');
  });

  return client;
}
Copy the code

Description of the callback method

// The connection succeeded
void onConnected() {
  print('Connected');
}

// The connection is disconnected
void onDisconnected() {
  print('Disconnected');
}

// Subscribed topic succeeded
void onSubscribed(String topic) {
  print('Subscribed topic: $topic');
}

// Failed to subscribe to the topic
void onSubscribeFail(String topic) {
  print('Failed to subscribe $topic');
}

// Unsubscribe successfully
void onUnsubscribed(String topic) {
  print('Unsubscribed topic: $topic');
}

// The PING response is received
void pong() {
  print('Ping response client callback invoked');
}
Copy the code

MqttConnectMessage: Sets connection options, including timeout Settings, authentication, and last wish messages.

Client.updates. Listen: Listens for the arrival of messages for subscribed topics.

Certificate Connection Example

/// Security context
SecurityContext context = newSecurityContext() .. useCertificateChain('path/to/my_cert.pem')
  ..usePrivateKey('path/to/my_key.pem', password: 'key_password')
  ..setClientAuthorities('path/to/client.crt', password: 'password');
client.secure = true;
client.securityContext = context;
Copy the code

Other MQTT operations

Subject to subscribe to

client.subscribe("topic/test", MqttQos.atLeastOnce)
Copy the code

News release

const pubTopic = 'topic/test';
final builder = MqttClientPayloadBuilder();
builder.addString('Hello MQTT');
client.publishMessage(pubTopic, MqttQos.atLeastOnce, builder.payload);
Copy the code

unsubscribe

client.unsubscribe('topic/test');
Copy the code

disconnect

client.disconnect();
Copy the code

test

We wrote a simple UI for the project and ran the following tests with MQTT X, the MQTT 5.0 client tool:

  • The connection

  • To subscribe to

  • release

  • unsubscribe

  • disconnect

Application interface:

Use MQTTX as another client to send and receive messages:

We can see the log of the whole process.

conclusion

We have completed the construction of an MQTT application on The Android platform using Flutter, enabling the client to connect to the MQTT server, subscribe, unsubscribe, send and receive messages, and so on.

With its unified development language and cross-platform nature, Flutter makes it easy to develop powerful mobile applications, and it may be the best solution for developing mobile applications in the future. With The combination of Flutter, the MQTT protocol and the MQTT cloud service, we can develop more interesting applications.

Copyright notice: this article is the original EMQ, reprint please indicate the source.

Link: www.emqx.io/cn/blog/usi…