0

I'm trying to automatically send a notification to a Flutter App whenever a specific value in my firestore changes. The cloud function is triggered but my App simply doesn't receive the message. I managed to get a message using the messaging in the firebase console, so I recon the cloud function doesn't send the message properly? I should also mention that I don't receive any errors.

A quick rundown of what I'm doing:

  1. Added a cloud function to my firebase project that listens to firestore changes
  2. Subscribed to the notification topic in my Flutter App
  3. Listened to the onMessage Event in my App

This is my cloud function

import * as functions from "firebase-functions";
import admin = require("firebase-admin");

admin.initializeApp();

exports.sendPhValueNotification = functions.firestore.document("/phValues/values").onUpdate(async (_, 
context) => {
   const phValue = context.params.ph;

   if (phValue < 7.2 || phValue > 7.8) {

    // Notification details.
    const payload = {
        topic: "phValues",
        notification: {
            title: `PH-Wert ${phValue < 7.2 ? "unter" : "über"} dem Richtwert!`,
            body: `Der PH-Wert im Whirlpool beträgt ${phValue}`
        }
    };

    // Send notifications to everyone
    await admin.messaging().send(payload);
}
});

And this is my setup in my Flutter App

await FirebaseMessaging.instance.subscribeToTopic('phValues');

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('Got a message whilst in the foreground!');
  print('Message data: ${message.data}');

  if (message.notification != null) {
    print('Message also contained a notification: ${message.notification}');
  }
});
pgr3931
  • 417
  • 4
  • 11
  • Have your followed the steps in FlutterFire? https://firebase.flutter.dev/docs/messaging/overview/ – Mäddin Apr 16 '21 at 01:05
  • Yes, that's where these code snippets are from. As you can see the onMessage Handler is the same as the one here https://firebase.flutter.dev/docs/messaging/usage#foreground-messages – pgr3931 Apr 16 '21 at 05:41

1 Answers1

0

Turns out it was just a dumb mistake on my part. The way I'm reading the value from the firestore is wrong and since I'm testing the value in the if statement, I never actually sennt a message.

This works now:

functions.firestore.document("/phValues/values").onUpdate(async (change) => {
const phValue = change.after.ph; // This line
pgr3931
  • 417
  • 4
  • 11