我想在收到来自 mqtt 代理的消息时推送通知

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

我正在开发 flutter 应用程序(当 raspberry pi 检测到移动时通知用户)。一切正常。

  1. 将 flutter 应用程序连接到 mqtt 代理
  2. 正在订阅主题
  3. 从 mqtt 代理获取消息,我可以在控制台日志中看到它们

我的问题是我想在收到来自 MQTT 代理的消息时推送通知。我试过“flutter_local_notification”,但我能找到的只是使用触发按钮的教程。

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);
    });
}

我找到了一个解决方案,我用“fluter_local_notification”创建了一个通知服务,然后当我收到来自 mqtt 代理的消息时我调用了 shownotification 函数。

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);
});

}