如何在Flutter中将MQTT消息转换为JSON格式

y4ekin9u  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(266)

我已经使用快照方法从MQTT代理连接并获取数据。但是,我想将MQTT消息转换为JSON格式,因为我想对某些数据做一些条件代码。
我的问题是,当我从MQTT代理流数据时,我的数据只显示了索引的最后一个数据。该索引包含三个不同的数据,但是由于索引同时包含三个数据,所以只显示了索引的最后一个数据。这是我当前的代码。我该怎么做呢?

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter MQTT"),
      ),
      body: FutureBuilder(
        future: mqttSubscribe(topic: "/sensor_simulator/data"),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasError) {
            return Center(
              child: Text("Error: ${snapshot.error}"),
            );
          }

          // if succeed to connect
          if (snapshot.connectionState == ConnectionState.done) {
            return StreamBuilder(
              stream: snapshot.data,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                // if have error--> display
                if (snapshot.hasError) {
                  return Center(
                    child: Text("Error: ${snapshot.error}"),
                  );
                }

                // if data detected--> display
                if (snapshot.hasData) {
                  try {
                    final List<MqttReceivedMessage> receiveMessage =
                        snapshot.data;
                    final recMess =
                        receiveMessage[0].payload as MqttPublishMessage;
                    String payload = MqttPublishPayload.bytesToStringAsString(
                        recMess.payload.message);

                    return ListView(
                      children: [
                        Card(
                            child: ListTile(
                          title: Text(payload),
                        ))
                      ],
                      padding: EdgeInsets.all(10),
                    );
                  } catch (e) {
                    return Center(
                      child: Text("Error: ${e.toString()}"),
                    );
                  }
                }

                return Center(child: CircularProgressIndicator());
              },
            );
          }

          return Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}
ovfsdjhp

ovfsdjhp1#

您可以使用这段代码:

void _subscribeToTopic(String topicName) {
  
  print('MQTTClientWrapper::Subscribing to the $topicName topic');
  client.subscribe(topicName, MqttQos.atMostOnce);

  client.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
  final recMess = c[0].payload as MqttPublishMessage;

  String message =
      MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
  String decodeMessage = Utf8Decoder().convert(message.codeUnits);

  print("MQTTClientWrapper::GOT A NEW MESSAGE $decodeMessage");
  
  });
}

相关问题