How do I send a notification to another user when one user presses a button? Can someone show me a code snippet?
I realize that this question was asked before, however, it was closed since there were "several answers." The links that were provided that were similar did not explain sending notifications in flutter.
CodePudding user response:
You will need Firebase Cloud Messaging for that.
The way I've done it is using a Cloud Function that you can trigger via HTTP or even via a Firestore trigger, like this:
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
/**
* Triggered by a change to a Firestore document.
*
* @param {!Object} event Event payload.
* @param {!Object} context Metadata for the event.
*/
exports.messageNotificationTrigger = (change, context) => {
db.collection('users').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
const userData = doc.data();
if (userData.id == '<YOUR_USER_ID>') {
admin.messaging().sendToDevice(userData.deviceToken, {
notification: {
title: 'Notification title', body: 'Notification Body'}
});
}
});
});
};
Every user you have registered in your users collection must have a device token, sent from their device they access the app.
From Flutter, using the FCM package, this is how you send the device token to Firebase:
// fetch the device token from the Firebase Messaging instance
// and store it securely on Firebase associated with this user uid
FirebaseMessaging.instance.getToken().then((token) {
FirebaseFirestore.instance.collection('users').doc(userCreds.user!.uid).set({
'deviceToken': token
});
});
Where userCredentials.user!.uid is the user you use to log in to your application using Firebase Authentication like this:
UserCredential userCreds = await FirebaseAuth.instance.signInWithCredential(credential);
Hope that helps.