當一個用戶按下按鈕時,如何向另一個用戶發送通知?有人可以給我看一個代碼片段嗎?
我意識到這個問題以前被問過,但是,由于有“幾個答案”,所以它被關閉了。提供的類似鏈接沒有解釋在flutter中發送通知。
uj5u.com熱心網友回復:
為此,您將需要 Firebase 云訊息傳遞。
我完成它的方式是使用可以通過 HTTP 甚至通過 Firestore 觸發器觸發的云函式,如下所示:
// 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'}
});
}
});
});
};
您在用戶集合中注冊的每個用戶都必須有一個設備令牌,從他們訪問應用程式的設備發送。
在 Flutter 中,使用FCM包,您可以通過以下方式將設備令牌發送到 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
});
});
其中userCredentials.user!.uid是您使用Firebase 身份驗證登錄應用程式的用戶,如下所示:
UserCredential userCreds = await FirebaseAuth.instance.signInWithCredential(credential);
希望有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/434601.html
