How do I send a message in Firebase Cloud Messaging to a spesific user from iniside the app?

Viewed 560

I configured firebase cloud messaging with my app and it works. I'm able to send test messages from the console and receive them on my app. Now I want to send messages to other users from inside the app. I made an inbox system and when I add new message to the user's inbox in firestore I also want to notify the user about it. I'm having hard time to figure out how to do it and I cant find anything helpful online. Currently, my code is:

FirebaseMessaging.instance.sendMessage(to: user.token, messageId: 'messageId');

The parameters for sendMessage are :

Future<void> sendMessage({
    String? to,
    Map<String, String>? data,
    String? collapseKey,
    String? messageId,
    String? messageType,
    int? ttl,
  })

The user's token is correct but I don't understand the other parameters. I tried adding the data parameter and the other parameters. I created a message in the console and tried putting its id in the messageId field but still it doesn't work and throw out this error:

Unhandled Exception: [firebase_messaging/unknown] null
MethodChannelFirebaseMessaging.sendMessage (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:356:7)

Can anyone explain how does it work and what am I doing wrong?

1 Answers

If you just used your token you would need to add @fcm.googleapis.com after it:

Future<void> sendMessage({
  String? to,
  Map<String, String>? data,
  String? collapseKey,
  String? messageId,
  String? messageType,
  int? ttl,
}) {
  if (ttl != null) {
    assert(ttl >= 0);
  }
  return _delegate.sendMessage(
    to: to ?? '${app.options.messagingSenderId}@fcm.googleapis.com',
    data: data,
    collapseKey: collapseKey,
    messageId: messageId,
    messageType: messageType,
    ttl: ttl,
  );
}

You can read more about it here and check here what all parameters are used for.

Pls also consider that this method is not used to send direct messages to other devices as explained here.

Related