3

I have devloped One to one chat system in flutter and want to send push notification to another device using FCM.

I have setup all the flutter and firebase messaging requirement.

//In InitState()
_firebaseMessaging.onTokenRefresh.listen(sendTokenToServer);
    _firebaseMessaging.getToken();
    _firebaseMessaging.configure(onLaunch: (Map<String, dynamic> msg) {
      print("onLaunch");
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Message(this.user, this.event)),
      );
    }, onResume: (Map<String, dynamic> msg) {
      print("onResume");
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Message(this.user, this.event)),
      );
    }, onMessage: (Map<String, dynamic> msg) {
      print("onMessage");
    });
    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, alert: true, badge: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings setting) {
      print("IOS");
    });

//sendTokenToServer() - function send FCM token my Postgres DB

//When user clicks on send Button

Future sendNotification(userData, eventData) async {
    await Messaging.sendToAll(
      title:
          "${toBeginningOfSentenceCase(userData['User']['name'])} on ${toBeginningOfSentenceCase(eventData['Event']['eventName'])} event",
      body: _messageController.text,
      fcmToken: fcmTokenToServer,
    );
  }

//Messaging.sendToAll()
static Future<Response> sendToAll(
          {@required String title,
          @required String body,
          @required String fcmToken}) =>
      sendTo(title: title, body: body, fcmToken: fcmToken);

  static Future<Response> sendTo({
    @required String title,
    @required String body,
    @required String fcmToken,
  }) =>
      client.post(
        'https://fcm.googleapis.com/fcm/send',
        body: json.encode({
          'notification': {'body': '$body', 'title': '$title'},
          'priority': 'high',
          'data': {
            'click_action': 'FLUTTER_NOTIFICATION_CLICK',
            'id': '1',
            'status': 'done',
          },
          'to': '$fcmToken',
        }),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'key=$serverKey',
        },
      );

But No push notification is receiving. Is it that I have to implement cloud functions to send notification??

Romil
  • 33
  • 1
  • 5

1 Answers1

11

I could send FCM messages from one device to other with the topic/FCM token without the server.

NOTE : Using the server key at client side is a bad practice and should not be used in production-level applications.

static Future<bool> sendFcmMessage(String title, String message) async {
    try {
      
      var url = 'https://fcm.googleapis.com/fcm/send';
      var header = {
        "Content-Type": "application/json",
        "Authorization":
            "key=your_server_key",
      };
      var request = {
        "notification": {
          "title": title,
          "text": message,
          "sound": "default",
          "color": "#990000",
        },
        "priority": "high",
        "to": "/topics/all",
      };

      var client = new Client();
      var response =
          await client.post(url, headers: header, body: json.encode(request));
      return true;
    } catch (e, s) {
      print(e);
      return false;
    }
}

If you have to send data request with FCM token, use

request = {
      'notification': {'title': title, 'body': message},
      'data': {
        'click_action': 'FLUTTER_NOTIFICATION_CLICK',
        'type': 'COMMENT'
      },
      'to': 'fcmtoken'
    };
Ruli
  • 2,592
  • 12
  • 30
  • 40
Shyju M
  • 9,387
  • 4
  • 43
  • 48
  • How can add this to topic `/topics/user-{userId}` which will send to particular device? – Romil Jun 19 '19 at 16:05
  • You can send with the fcmtoken only, cannot use topic with userid – Shyju M Jun 20 '19 at 05:58
  • 1
    *firebaser here* Using `"key=your_server_key"` in client-side code is a serious security risk, as it allows malicious users to send whatever message they want to your users. This is a bad practice and should not be used in production-level applications. For a better approach, see https://fireship.io/lessons/flutter-push-notifications-fcm-guide/ and my answer here: https://stackoverflow.com/a/57842615 – Frank van Puffelen Dec 16 '19 at 04:52