Fifis
Fifis

Reputation: 218

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 [email protected] and [email protected]
  2. user login to [email protected]
  3. other user send notification to [email protected]
  4. notification will be send on both accounts ([email protected] and [email protected]) instead of only to [email protected]

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!

Upvotes: 2

Views: 3047

Answers (1)

Fifis
Fifis

Reputation: 218

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

Upvotes: 1

Related Questions