I cannot access incoming data while listening to mqtty in flutter

Viewed 85

While listening to mqtty in flutter, I cannot access the incoming data from the main class. I want to assign the data from the topic I am listening to a variable and access it from the main class. for example title: Text(mqttconnect().pt1.toString()) I want to print the data from mqtt into text in main class.

import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

// ignore: camel_case_types
class mqttconnect {
  String? pt1;

  MqttServerClient? client =
      MqttServerClient.withPort('192.168.1.147', 'clientId-4ErbOoPajY', 1883);

  connect(String? top, String? left) async {
    final connMessage = MqttConnectMessage()
        .keepAliveFor(60)
        .withWillTopic('kare')
        .withWillMessage('$left,$top')
        .startClean()
        .withWillQos(MqttQos.atLeastOnce);
    client?.connectionMessage = connMessage;
    try {
      await client?.connect();
    } catch (e) {
      print('Exception: $e');
      client?.disconnect();
    }
    const topic = 'kare'; // Not a wildcard topic
    client?.subscribe(topic, MqttQos.atMostOnce);
    client?.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
      final recMess = c![0].payload as MqttPublishMessage;
      String pt =
          MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
      pt1 = pt;
    });
  }
}



Hello everyone. While listening to mqtt in Flutter, I cannot transfer from pt to pt1. pt1 returns null every time. I want to transfer the incoming pt values to pt1 by calling them from the main class. But pt1 always returns null. Can you help me?

1 Answers

You need to decode the value of "pt"

pt1 = json.decode(pt);

and to get access to the value of the pt1, you need to use a state management like GetX, provider or any other

Related