我看到的每个示例都与下面的代码几乎相同。出于某种原因,这对我不起作用。问题是当我尝试分配 final MqttPublishMessage message
时,它说 c[0].payload
的类型为“MqttMessage”,不能分配给“MqttPublishMessage”类型的变量。
MqttServerClient client = new MqttServerClient(serverUri, clientId);
client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c){
final MqttPublishMessage message = c[0].payload; // Cannot assign type
final payload = MqttPublishPayload.bytesToStringAsString(message.payload.message);
print('Received message:$payload from topic: ${c[0].topic}>');
});
我试过铸造也不起作用。我已经完全复制了代码,但似乎没有任何效果。这是怎么回事?
答案 0 :(得分:1)
这是提供的完整示例here
client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
final recMess = c![0].payload as MqttPublishMessage;
final pt =
MqttPublishPayload.bytesToStringAsString(recMess.payload.message!);
/// The above may seem a little convoluted for users only interested in the
/// payload, some users however may be interested in the received publish message,
/// lets not constrain ourselves yet until the package has been in the wild
/// for a while.
/// The payload is a byte buffer, this will be specific to the topic
print(
'EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');
print('');
});
正如你所看到的,他正在创建没有类型的变量,并且正在进行重铸:
final recMess = c![0].payload as MqttPublishMessage;
如果这不起作用,我会在客户端设置中查找一些错误,或者您接收的数据可能与您期望接收的数据不完全相同。