Search code examples
androidflutterdartpush-notificationmqtt

i want to push notification when i recieve a message from mqtt broker


I'm working on flutter app ( notify user when a raspberry pi detect a movement). Everything works fine.

  1. connecting the flutter app to mqtt broker
  2. subscribing to the topic
  3. getting the messages from the mqtt broker and i can see them in console log

My problem is that I want to push notification when I get a message from MQTT broker. i tried "flutter_local_notification" but all what I could find is tutorials working with triger buttons.

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

    // print the message when it is received
    client.updates?.listen((List<MqttReceivedMessage<MqttMessage>>? c) {
      final recMess = c![0].payload as MqttPublishMessage;
      final message =
          MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
      print('YOU GOT A NEW MESSAGE:');
      // i want to push notifation
      print(message);
    });
}

Solution

  • i found a solution , i created a notification service with "fluter_local_notification" then i called the shownotification function when i get a message from mqtt broker.

    void _subscribeToTopic(String topicName) {
    print('Subscribing to the $topicName topic');
    
    client.subscribe(topicName, MqttQos.atMostOnce);
    
    // print the message when it is received
    client.updates?.listen((List<MqttReceivedMessage<MqttMessage>>? c) {
      final recMess = c![0].payload as MqttPublishMessage;
      final message =
          MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
      print('YOU GOT A NEW MESSAGE:');
      // i want to push notifation
      NotificationService()
          .showNotification(1, 'check your mailbox', 'you have new mail', 1);
      print(message);
    });
    

    }