3

I have a flutter app that in some point the administrator users can save one publication.

Now I want all users receive a notification when that publication is posted (with it title, description ..etc).

How could I do that with firebase messaging?

I already wrote this code which, if I go to firebase console and generate a example notification, I receive it normally:

class PushNotificationsManager {

  PushNotificationsManager._();

  factory PushNotificationsManager() => _instance;

  static final PushNotificationsManager _instance = PushNotificationsManager._();

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  Future<void> init() async {
    if(Platform.isIOS){
      _firebaseMessaging.requestNotificationPermissions(IosNotificationSettings());
    }
    _firebaseMessaging.configure(
      // Called when the app is in the foreground and we receive a push notif.
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
        print(message['notification']['body']);

      },
      // Called when the app has been closed completely and its opened
      // from the notification directly
      onLaunch: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
      },
      // Called when the app is in the background and its opened from the notif
      onResume: (Map<String, dynamic> message) async {
        print("onMessage: ${message}");
      },
    );
}

In summary, how could I generate a notification (with the title and description created) to all users when the admin creates a new publication without going to firebase console to generate it manually?

  • I'm using firebase_messaging: ^7.0.3

Update I tried to do this:

Future sendNotification() async {
    final String url = 'https://fcm.googleapis.com/fcm/send';
    var token = await _firebaseMessaging.getToken();
    var data;
    data='{"notification": {"body": "this is a body", "title": "this is a title"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK"}, "to": "${token}"}';
    final response = await http.post(
      url,
      headers: <String, String>{"Content-Type": "application/json", "Keep-Alive" : "timeout=5", "Authorization" : "key=${mykey}"},
      body: data
    );

    print(response.body);
  }

...calling this in the method I save the event in firebase only displays the notification to my phone, and not to every phone, there's a way to do it in this form?

HelloWorldd
  • 172
  • 2
  • 14
  • 2
    *firebaser here* Sending messages **to** other user through FCM requires that you specify the FCM server key in the API call. As its name implies this key should only be used on a server (or otherwise trusted environment like Cloud Functions) as it allows anyone who has it to send whatever message they want to any of your users. By embedding this FCM server key in the the Flutter app that you give to your users, you open them up to abuse and spam and it's a serious security risk. – Frank van Puffelen Jan 07 '21 at 16:11
  • Thanks for the answer, so how do you suggest me to do it? – HelloWorldd Jan 07 '21 at 16:40
  • 2
    As the documentation shows it: https://firebase.google.com/docs/cloud-messaging/fcm-architecture So from a trusted environment, such as your development machine, a server that you control, or Cloud Functions. Also see my answer here: https://stackoverflow.com/questions/37990140/how-to-send-one-to-one-message-using-firebase-messaging/37993724#37993724 – Frank van Puffelen Jan 07 '21 at 16:57

1 Answers1

2

You can do this using a cloud function. Either by calling the function from your app when the publication is created, or by having the cloud function listen for a new document. See this Medium post for some ideas: https://medium.com/@jerinamathews/send-firebase-cloud-messaging-fcm-to-a-topic-using-cloud-function-when-realtime-database-value-fa78fa758549

Update

Based on your update, I suggest you look at using a 'Topic' rather than a specific token (that applies to only one device). To use a Topic you need to ensure all users automatically subscribe to the chosen topic when they open the app (they can subscribe to the same topic each time, it has no negative impact). FCM maintains a list of subscribed device tokens against the topic.

I haven't used topic via an http post so I cannot confirm it is possible but I am assuming if you can send to a token you must be able to send to a topic.

GrahamD
  • 2,952
  • 3
  • 15
  • 26
  • Please mark it as the accepted answer (click the tick) if you are happy with it. :-) – GrahamD Jan 07 '21 at 14:07
  • Thanks for your answer, please see my update, initially I'm trying in another way. – HelloWorldd Jan 07 '21 at 14:27
  • But in your example, the article says 'realtime database' and i'm storing my data in the Firestore – HelloWorldd Jan 07 '21 at 16:37
  • The database you use is nothing to do with FCM, you could be using your own sql server. You need to read the docs on FCM, calling it from the client, cloud functions, etc. – GrahamD Jan 07 '21 at 16:48