0

I have Firebase Cloud Messaging set up for my app in Flutter. I have set up everything on the console. I also tested with postman which also works well. However, I also want to test within Flutter by which I know is possible too.

But it doesn't work for me as I do not any notification nor error message. How can this be done?

Future<Map<String, dynamic>> sendAndRetrieveMessage() async {
    print("Wdwd");
    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: jsonEncode(
        <String, dynamic>{
          'notification': <String, dynamic>{
            'body': 'this is a body',
            'title': 'this is a title'
          },
          'priority': 'high',
          'data': <String, dynamic>{
            'click_action': 'FLUTTER_NOTIFICATION_CLICK',
            'id': '1',
            'status': 'done'
          },
          'to': "tokenString",
        },
      ),
    );

    final Completer<Map<String, dynamic>> completer =
    Completer<Map<String, dynamic>>();
    firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        completer.complete(message);
      },
    );
    return completer.future;
  } 

I initiate this code with a button click. Didn't get any response. Please help me out.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
bensofter
  • 760
  • 1
  • 14
  • 27
  • Including this `'Authorization': 'key = $serverToken'` in an application that you send to your users is a serious security risk. As its name applies, that token should only be used in a trusted environment, such as your development machine, a server you control, or Cloud Functions. Using the FCM server key in an app as you do here, means that a malicious user can take it from there, and use it to send any message *they* want to any of *your* users. Securely sending device-to-device messages requires that you set up a server, as shown here: https://stackoverflow.com/a/37993724 – Frank van Puffelen Mar 29 '20 at 15:30

1 Answers1

0

Assuming that you are developing a backend app that sends push notification to other users, and you are using the code example given in here

First go to Firebase Console - Settings - Project Settings - Cloud Messaging

Then copy the token associated with the server key and use it as a server token

final String serverToken = '<The token you copied goes here>';

Well that's how I got it working. There might be some security issues as pointed out earlier

zizutg
  • 1,070
  • 14
  • 20