2

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?

2
  • Hm, that's strange. But mine is final String payload = MqttPublishPayload.bytesToStringAsString(message.payload.message);
    – adadion
    Jun 16, 2021 at 8:24
  • Also it might be a typo. See --> print('Received message:$payload from topic: <${c[0].topic}>');
    – adadion
    Jun 16, 2021 at 8:26

1 Answer 1

3

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.

2
  • final recMess = c![0].payload as MqttPublishMessage; fixed my IDE error. I actually got a suggestion saying c![0] will never be null. Upon running, I got an error saying client.updates!.listen was selecting a null object but that I fixed it with client.updates?.listen. Jun 16, 2021 at 19:07
  • That's becouse of Null Safety. It has been introduced with Flutter 2.0. flutter.dev/docs/null-safety
    – L. Gangemi
    Jun 16, 2021 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.