Flutter / Firebase-向用户发送通知

时间:2020-02-10 12:33:17

标签: firebase flutter dart firebase-cloud-messaging

目标:发送所有用户设备的通知。

问题描述:我在为一个用户发送通知时遇到问题。注册后,我将FCM令牌存储在数据库中,以供用户发送通知给他。问题是,当用户要注册多次时-同一令牌将为多个用户存储。

示例:

  1. 用户通过电子邮件test@gmail.com和test2@gmail.com注册
  2. 用户登录到test@gmail.com
  3. 其他用户将通知发送到test@gmail.com
  4. 通知将同时在两个帐户(test@gmail.com和test2@gmail.com)上发送,而不是仅发送到test@gmail.com

这是我的问题-如何将通知发送到与该用户连接的所有设备而不是与该设备连接的所有用户?

QuerySnapshot ref = await Firestore.instance.collection('users')
    .document(_textController.text)
    .collection('tokens')
    .getDocuments();

ref.documents.forEach((snapshot) async {
  http.Response response = await http.post(
    'https://fcm.googleapis.com/fcm/send',
    headers: <String, String>{
      'Content-Type': 'application/json',
      'Authorization': 'key=$serverKey',
    },
    body: jsonEncode(
      <String, dynamic>{
        'notification': <String, dynamic>{
          'body': 'this is a body',
          'title': 'this is a title'
        },
        'priority': 'high',
        'data': <String, dynamic>{
          'click_action':
          'FLUTTER_NOTIFICATION_CLICK',
          'id': '1',
          'status': 'done'
        },
        'to': snapshot.data['token'],
      },
    ),
  );
});

感谢帮助!

1 个答案:

答案 0 :(得分:1)

我找到了解决方案!

如果遇到同样的问题,您要做的就是在注销时删除令牌。

final Firestore store = Firestore.instance;
final FirebaseAuth auth = FirebaseAuth.instance
String token = await _fcm.getToken();
await store
    <reference to token document>
    .delete();
await auth.signOut();