Send unique Firebase push notifications to users on Flutter app

1,381

Solution 1

to send a push notification to a related subject your user should be subscribed to it:

final FirebaseMessaging _fcm = FirebaseMessaging();

...

FlatButton(
    child: Text('I like puppies'),
    onPressed: () => _fcm.subscribeToTopic('puppies');,
),

FlatButton(
    child: Text('I hate puppies'),
    onPressed: () => _fcm.unsubscribeFromTopic('puppies');,
),

and on backend side(NodeJS):

export const sendToTopic = functions.firestore.document('puppies/{puppyId}').onCreate(async snapshot => {
const puppy = snapshot.data();

const payload: admin.messaging.MessagingPayload = {
  notification: {
    title: 'New Puppy!',
    body: `${puppy.name} is ready for adoption`,
    icon: 'your-icon-url',
    click_action: 'FLUTTER_NOTIFICATION_CLICK' // required only for onResume or onLaunch callbacks
  }
};

return fcm.sendToTopic('puppies', payload);});

There is a good tutorial how to do it: link

Solution 2

I don't have a strong experience on backend, but there are two approaches I could provide.

we want to be able to find all the users that match that post

A. You should store FCM token per account, and bind the user with relative posts. When you found out that the posts are matched. Use firebase-admin to send notifications. You should have the users that have one to one relation on FCM token in database.

B. More Advanced, you could register a bunch of relative users to certain topic, and send It once as broadcasting.

Again, I don't think my approach is the best practice to use FCM, If there are any errors, please leave a comment or answer!

Share:
1,381
Hani Honey
Author by

Hani Honey

Updated on December 13, 2022

Comments

  • Hani Honey
    Hani Honey over 1 year

    I've got a Flutter app that connects to a database built on Laravel. In essence, our users will have a profile, and their profile will match with certain kinds of posts. Whenever a new post is added, we want to be able to find all the users that match that post, and send them a push notification that they have been matched to a newly added post.

    I am looking for, in theory, a good method for how to do this as right now I am a bit in the dark and don't have a lot of experience with Firebase and push notifications.

  • Hani Honey
    Hani Honey over 4 years
    Hi, thank you for your reply! What if, in my case, the user has more specific criteria that they need to match a post on? We cod use jobs as an example. There are more than one criteria that the user has selected that could help them match on jobs. Is this not possible?
  • Stellar Creed
    Stellar Creed over 4 years
    difficult to say right now. maybe you subscription should be like "post_economics", "post_business" and so on + a lot of conditions on backend side to send a push notification or not according to those types