skip to Main Content

Firebase functions:

const functions = require("firebase-functions");
const admin = require('firebase-admin');

admin.initializeApp();

exports.chatNotifications = functions.firestore.document("chat/{docId}").onCreate(
    (snapshot, context) => {
        admin.messaging().sendToTopic(
            "chat", 
            {
                notification: {title: "New message", body: "A new message has been sent"}, 
                data: {click_action: "FLUTTER_NOTIFICATION_CLICK"},
            }
        );

    }

);

Flutter:


Future<void> backgroundHandler(RemoteMessage message) async{
    print(message.notification!.body.toString());
}

void main{
    FirebaseMessaging.instance.subscribeToTopic("chat");
    FirebaseMessaging.onBackgroundMessage(backgroundHandler);
}

pubspec.yaml:

firebase_core: ^2.1.1
firebase_auth: ^4.1.0
cloud_firestore: ^4.0.3
firebase_messaging: ^14.0.4
flutter_local_notifications: ^12.0.3

It works when I send a notification from the firebase console.
I don’t get anything from firebase functions.

2

Answers


  1. Chosen as BEST ANSWER

    Go to Google cloud console api library.

    Select your project at the top left of your screen.

    Search for "cloud messaging".

    Enable cloud messaging, firebase cloud messaging api and fcm registration api.


  2. For background triggers which in this case is onCreate trigger, You have to return a promise to tell function your work is completed, or function will close unexpectedly.

    So return sendToTopic() which is a promise.

       return admin.messaging().sendToTopic(
                "chat", 
                {
                    notification: {title: "New message", body: "A new message has been sent"}, 
                    data: {click_action: "FLUTTER_NOTIFICATION_CLICK"},
                }
            );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search