Lor*_*kel 2 flutter google-cloud-functions firebase-cloud-messaging
对于 flutter 应用程序 I\xe2\x80\x99m 使用 Firebase Cloud Messaging 和云功能通过用户的 FCM 注册令牌向用户发送推送通知。该应用程序有一个设置页面,用户应该能够在其中关闭某些推送通知。通知是特定于用户的,因此订阅或取消订阅的主题不起作用,但通知可以分为某些类别。
\n\n例如,在聊天应用程序中,当用户 A 向用户 B 发送消息时,推送通知可能属于 \xe2\x80\x98chat messages\xe2\x80\x99 类别,而用户 A 也可以删除与用户 B 的聊天记录,并且该推送通知可能属于 \xe2\x80\x98deleted chats\xe2\x80\x99 类别。
\n\n如何才能让用户 B 关闭 \xe2\x80\x98deleted chats\xe2\x80\x99 的通知,同时仍接收 \xe2\x80\x98chat messages\xe2\x80\x99 的通知?是否可以以一种方式使用带有主题和 user\xe2\x80\x99s 注册令牌的条件?任何想法都将不胜感激!
\n感谢道格在正确方向上的大力推动,我终于弄清楚了!在下面发布我的代码以帮助任何人朝着正确的方向采取相同的步骤。
因此,在我的 flutter 应用程序的设置页面中,用户可以打开和关闭几个类别的通知。然后,用户的首选项将存储在我的 Cloud Firestoreusers集合中的用户特定文档中。SwitchListTile请参阅下面的代码,了解我在设置页面上使用的示例。
SwitchListTile(
title: Text('Admin notifications'),
subtitle: Text('Maintenance and general notes'),
onChanged: (value) {
setState(() {
adminNotifications = value;
Firestore.instance
.collection('users')
.document(loggedInUser.uid)
.updateData({
'adminNotifications': value,
});
});
save('adminNotifications', value);
},
value: adminNotifications,
),
Run Code Online (Sandbox Code Playgroud)
在我的云函数中,我添加了对集合中文档的引用users,并检查该字段的值是否adminNotifications等于true。如果是,则发送通知,否则不向用户发送通知。下面我添加了云功能。请注意,云函数会呈现“嵌套承诺”警告,但它目前有效!我仍然是 Flutter 初学者,所以我很高兴能够让它发挥作用。再次非常感谢道格!
exports.userNotifications = functions.firestore.document('notifications/{any}').onCreate((change, context) => {
const userFcm = change.data().fcmToken;
const title = change.data().title;
const body = change.data().body;
const forUser = change.data().for;
const notificationContent = {
notification: {
title: title,
body: body,
badge: '1',
click_action: 'FLUTTER_NOTIFICATION_CLICK',
}
};
var usersRef = db.collection('users');
var queryRef = usersRef.where('login', '==', forUser).limit(1).get()
.then(snapshot => {
snapshot.forEach(doc => {
const adminNotifications = doc.data().adminNotifications;
console.log(adminNotifications);
if(swapNotifications === true){
return admin.messaging().sendToDevice(userFcm, notificationContent)
.then(() => {
console.log('notification sent')
return
})
.catch(error =>{
console.log('error in sending notification', error)
})
} else {
console.log('message not send due to swapNotification preferences')
}
return console.log('reading user data success');
})
.catch(err => {
console.log('error in retrieving user data:', err)
})
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7227 次 |
| 最近记录: |