0

I am trying to send firebase push notifications via Flutter. Below is the code

Future<Map<String, dynamic>> sendAndRetrieveMessage(String fcmToken, String title, String msg) async {

    await _firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(
          sound: true, badge: true, alert: true, provisional: false),
    );

    await http.post(
      'https://fcm.googleapis.com/fcm/send',
      headers: <String, String>{
        'Content-Type': 'application/json',
        'Authorization': 'key=$serverToken',
      },
      body: convert.jsonEncode(
        <String, dynamic>{
          'notification': <String, dynamic>{'body': msg, 'title': title},
          'priority': 'high',
          'data': <String, dynamic>{
            'click_action': 'FLUTTER_NOTIFICATION_CLICK',
            'id': '1',
            'status': 'done'
          },
          'to': fcmToken,
        },
      ),
    ).then((http.Response response){
      final int statusCode = response.statusCode;

        print("RESPONSE: " + response.body);
        print("STATUS CODE: " + statusCode.toString());

        if (statusCode < 200 || statusCode > 400 || response.body == null) {
          throw new Exception("Error while fetching data");
        }
    });
  }

Below is the error I get

RESPONSE: {"multicast_id":8498089791993785359,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}

Surprisingly, I can use the same FCM Token via the Firebase UI console to send messages. It simply works.

Update

for the to field, If I use the code await _firebaseMessaging.getToken() I dont get the error and it get passed.The above is for getting the FCM of the same user, which is a string.

I know my fcm token of other users are not incorrect, because when used in Firebase console, it works.

What is the issue here?

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • can you share th error – HII Apr 22 '20 at 17:44
  • @LoVe: Sorry, forgot it. I updated the post – PeakGen Apr 22 '20 at 18:02
  • this is not using flutter but it may be the same issue for you please have a look https://stackoverflow.com/q/42241432/9142279 – HII Apr 22 '20 at 18:06
  • @LoVe: I dont think that is the issue. I am using the server key – PeakGen Apr 22 '20 at 18:08
  • ok sorry for too many redirections but did you check this also?it may contain steps that can solve your problem as they are getting your same error https://github.com/flutter/flutter/issues/30486 – HII Apr 22 '20 at 18:13

1 Answers1

0

The error was a simple mistake, I figured it out. In the notification receiving application, I was registering my self with FCM at the register page as well as in the login page. I only save the token generated in the registration, so I simply don't have the new token generated a the login page.

Solution is to eliminate the FCM registration code in login page.

PeakGen
  • 21,894
  • 86
  • 261
  • 463