简体   繁体   中英

Flutter/Firebase - sending notification to user

Goal: send notification for all user devices.

Problem description: I've problem with sending notification for one user. After registration, I store FCM token in database for user to send notification for him. Problem is that when user will register multiple times - same token will be stored for more than one user.

Example:

  1. user register with emails test@gmail.com and test2@gmail.com
  2. user login to test@gmail.com
  3. other user send notification to test@gmail.com
  4. notification will be send on both accounts (test@gmail.com and test2@gmail.com) instead of only to test@gmail.com

So here's my question - how to send notification to all devices connected to user instead of all users connected with device?

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'],
      },
    ),
  );
});

Thanks for help!

I FOUND SOLUTION!

All you have to do if you have the same problem is deleting token on logout.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM