Romero Henrique
Romero Henrique

Reputation: 13

Show background notification using conditions - Flutter

I am developing an App where the user will receive a notification if any other user likes his picture.

I'm able to handle in-App notification and apply my conditions without any problem.

Unfortunately, I am not able to handle the background Notification.

This is what I did so far:

 FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  if (1 > 1) {
    print('send it');
    return true;
  } else {
    print('don\'t send it');
    return false;
  }
}

No matter what I do under _firebaseMessagingBackgroundHandler, notification will be shown anyways.

My handler is triggered and I can see the print in Console.

I believe there is another handle inside the FCM SDK that handles this notification, and the FirebaseMessaging.onBackgroundMessage is just an option.

Any thoughts? thank you!

Upvotes: 1

Views: 2304

Answers (1)

Saiful Islam
Saiful Islam

Reputation: 1269

The way you are trying to handle the background message is fine but there is more to know how the FCM really works.

First of all, Firebase Provide us two types of messaging

  1. Notification Message

    FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user- visible keys and an optional data payload of custom key-value pairs

  2. Data Message

    The client app is responsible for processing data messages. Data messages have only custom key-value pairs with no reserved key names

Now for your scenario, you should send your message from Firebase as Data Message then you have control of it, otherwise, if you send the Notification Message from Firebase the notification will show automatically.

Here are example sample snippets of two different types of Firebase Message

  1. Notification Message:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}

  1. Data Message

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"
    }
  }
}

And finally, I recommend you take a look at the official documentation About FCM message.

Upvotes: 1

Related Questions