MQTT In Flutter Application

Introduction:

In today's interconnected world, real-time communication is essential for many applications. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for efficient communication between devices. Combining MQTT with Flutter, a versatile UI toolkit by Google, can empower your mobile applications with real-time capabilities. In this blog post, we will delve into MQTT connectivity within Flutter applications and discover how it can elevate the functionality and user experience of your apps.

Understanding MQTT:

MQTT is a lightweight and efficient messaging protocol designed for devices with limited processing power and low-bandwidth, high-latency, or unreliable networks. MQTT follows a publish-subscribe architecture, where clients (devices or applications) publish messages to topics, and other clients subscribe to those topics to receive messages. MQTT's simplicity, low overhead, and support for Quality of Service (QoS) levels make it an ideal choice for real-time communication.

 

Here's a step-by-step guide and a simple code for creating a Flutter app that  listens to MQTT messages:

Step 1: Add dependencies:

To start using MQTT in your Flutter application, you need a suitable MQTT package. One of the most popular packages is the “mqtt_client” package. Here's how you can add it to your “pubspec.yaml” file:

Step 2: Import the Package:

Import the ‘mqtt_client’ package in your Dart file where you want to use MQTT:

4

Step 3: Create the MQTT Client:

We import the required packages from the mqtt_client library.We create an instance of MqttServerClient with the MQTT broker's URL, a client ID, and the MQTT broker's port. You should replace 'mqtt_broker_url' and 'client_id' with your specific MQTT broker's URL and a unique client ID.We configure a MqttConnectMessage that includes settings such as the client identifier, connection options, and last will and testament settings.We attempt to connect to the MQTT broker using the await client.connect(); statement. If the connection is successful, it prints a message indicating that it's connected. If there's an error, it prints an error message.

 

class _MyHomePagesState extends State  {

  late MqttServerClient _mqttClient;
  final String server = "your-server-url";
  final int port = 1883;
  final String clientId = "unique-client-ID";
  final String topic = "your-topic-name";

  @override
  void initState() {
    super.initState();
    _initializeMqttScreen();

  }

  Future _initializeMqttScreen() async {
    _mqttClient = MqttServerClient(server, clientId);
    _mqttClient.logging(on: true);

    try {
      await _mqttClient.connect();
    } catch (e) {
      print("Error connecting to MQTT Broker: $e");
      return;
    }

 

Step 4: Subscribe to MQTT Topics:

Once the MQTT client is connected, you can subscribe to MQTT topics to start listening for messages. we can add a condition if MQTT status is connected with specific MQTT Topic. It listens to updates from the broker and prints received messages to the console. The listen method on the client's updates stream is used to handle incoming messages.

if (_mqttClient.connectionStatus?.state == MqttConnectionState.connected) {
      print("Connected to MQTT Broker");

      _mqttClient.subscribe(topic, MqttQos.exactlyOnce);


      _mqttClient.updates?.listen((List> messages) async {
        final MqttPublishMessage message = messages[0].payload as MqttPublishMessage;
        final String payloadmessage = MqttPublishPayload.bytesToStringAsString(message.payload.message);
        Map jsonMap = jsonDecode(payloadmessage);

        print('Received message on topic $topic: $payloadmessage');
      }
      );
    }
    else
    {
      print("Failed to connect to MQTT Broker");
    }
  }

Step 5:Disconnected from MQTT:

When you're finished listening to MQTT messages, the disconnectFromMqtt function can be called to gracefully disconnect from the MQTT broker. It closes the connection and prints a message indicating the disconnection.

void disconnectFromMqtt() {
      if (_mqttClient != null) {
        _mqttClient!.disconnect();
        print('Disconnected from the MQTT broker');
      }
    }

    @override
    void dispose() {
      disconnectFromMqtt();
      super.dispose();
    }

Here’s it is a full sample code:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';



class MyHomePages  extends StatefulWidget {
  @override
  _MyHomePagesState createState() => _MyHomePagesState();
}

class _MyHomePagesState extends State  {

  late MqttServerClient _mqttClient;
  final String server = "your-server-url";
  final int port = 1883;
  final String clientId = "unique-client-ID";
  final String topic = "your-topic-name";

  @override
  void initState() {
    super.initState();
    _initializeMqttScreen();

  }

  Future _initializeMqttScreen() async {
    _mqttClient = MqttServerClient(server, clientId);
    _mqttClient.logging(on: true);

    try {
      await _mqttClient.connect();
    } catch (e) {
      print("Error connecting to MQTT Broker: $e");
      return;
    }

    if (_mqttClient.connectionStatus?.state == MqttConnectionState.connected) {
      print("Connected to MQTT Broker");

      _mqttClient.subscribe(topic, MqttQos.exactlyOnce);


      _mqttClient.updates?.listen((List> messages) async {
        final MqttPublishMessage message = messages[0].payload as MqttPublishMessage;
        final String payloadmessage = MqttPublishPayload.bytesToStringAsString(message.payload.message);
        Map jsonMap = jsonDecode(payloadmessage);

        print('Received message on topic $topic: $payloadmessage');
      }
      );
    }
    else
    {
      print("Failed to connect to MQTT Broker");
    }
  }

    void disconnectFromMqtt() {
      if (_mqttClient != null) {
        _mqttClient!.disconnect();
        print('Disconnected from the MQTT broker');
      }
    }

    @override
    void dispose() {
      disconnectFromMqtt();
      super.dispose();
    }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MQTT Subscriber'),
      ),
    );
  }
}

Conclusion:

In this blog post, we explored how to create an MQTT listener in a Flutter application using the mqtt_client package. MQTT (Message Queuing Telemetry Transport) is a lightweight and efficient protocol commonly used in IoT (Internet of Things) and real-time messaging applications. We learned how to set up an MQTT client, connect it to an MQTT broker, and subscribe to MQTT topics to listen for incoming messages.

Don’t hesitate to contact us any time

Our experts can help you accelerate your digital transformation journey!

Call Us For Any inquiry

+91 9054325004