Reputation: 610
Every example I see is nearly identical to the code below. For some reason, this does not work form me. The problem is when I try to assign final MqttPublishMessage message
, it is saying that c[0].payload
is of type 'MqttMessage' which cannot be assigned to a variable of type '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}>');
});
I've tried casting which also doesn't work. I've copied the code exactly and nothing seemed to work. What is going on?
Upvotes: 2
Views: 1127
Reputation: 3300
That's the full example provided 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('');
});
As you can see he's creating the variable without the type, and he's doing a recast:
final recMess = c![0].payload as MqttPublishMessage;
If this doesn't works, I would look for some errors in the client setup or maybe the data you are receiveing is not exactly what you are expecting to receive.
Upvotes: 3