多亏了 Doug 在正确方向上的大力推动,我才得以弄清楚!在下面发布我的代码,以帮助任何人朝着正确的方向迈出相同的一步。
因此,在我的 Flutter 应用程序的设置页面中,用户可以打开和关闭几个类别的通知。然后,用户的首选项存储在我的 Cloud Firestore users 集合中的用户特定文档中。我在设置页面上使用的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,
),
在我的云函数中,我在users 集合中添加了对文档的引用,并检查adminNotifications 字段的值是否等于true。如果是,则发送通知,否则不向用户发送通知。下面我添加了云功能。请注意,云函数会呈现 'nested promises' 警告,但它现在有效!我仍然是 Flutter 的初学者,所以我很高兴能够让它工作。再次感谢 Doug!
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)
})
});