Integrating Push Notification in your Flutter App using Firebase Cloud Messaging REST API

Caleb Jesusegun
12 min readMay 19, 2023

--

Have you ever stopped using an app simply because you forgot it was on your mobile device? Or let’s imagine a mobile developer who released an app on both stores but after a month realized users are not returning to the app after the initial download due to low user engagements. One of the expected immediate response would be to reach out to the users to keep them up-to-date with the latest content and new release.

This proves the fact that staying connected with the users of your mobile app is an essential factor to consider to boost user engagement and drive conversions. With Firebase Cloud Messaging, you can achieve all these seamlessly by integrating push notification in your mobile app. It provides a direct line of communication between you and your users, allowing you to send them timely and relevant feature updates.

In this article, we will take a deep dive into Firebase Cloud Messaging and it’s REST API and how to integrate push notification in a sample flutter app. Specifically, we’ll cover:

  • What is Firebase Cloud Messaging
  • Benefits of Integrating Firebase Cloud Messaging in your Flutter app
  • How Firebase Cloud Messaging works
  • Firebase Cloud Messaging in Use: Integrating Push Notification in your Flutter app
  • Testing our sample app
  • Conclusion

Let’s get right into it

What is Firebase Cloud Messaging

I know you’re wondering firebase, cloud and messaging, what’s the connection?

Well, like the name suggest Firebase Cloud Messaging (FCM) is a cloud-based solution service provided by Firebase to allow developers send notification message to the mobile device of their users. The notification message can be received either when the app is open and in use or when the app is open but in the background. FCM also provides a platform to send targeted notification message to a specific group of users at once or at specific times and intervals.

FCM is easy to use and has support for both Android and iOS devices. It has the ability to deliver notification messages to a large number of devices in real-time.

Benefits of Firebase Cloud Messaging

Some of the key benefits of Firebase Cloud Messaging include:

  1. Sending notification messages: With FCM, you can send notification messages displayed in your users mobile device or send data messages to determine what happens when a user click on the notification. These notification messages appear as pop-ups or alerts to enable you engage with the users of your app.
  2. Device message targeting: With FCM, you can send different messages to either a single device, a group of devices, or to devices subscribed to topics. This allows you to target specific devices or user groups by language, location, or device type.
  3. Monitor notification analytics: With FCM, you have access to real-time analytics and insights on the message delivery and engagement. This makes it possible to track and optimize messaging strategy based on user behavior.

To further understand fcm architecture check out the documentation for an indepth explanation.

How Firebase Cloud Messaging Works

Now the concept of firebase cloud messaging is dependent on two main factors for sending and receiving notification:

  • There’s a trusted environment such as Cloud Functions and Notification composer on the firebase console or an app server using FCM REST API.
  • Then there’s the users mobile device that receives the messages via the platform-specific transport service.

What this means is that there’s a client side which is usually the users device and a server side where the notification is initiated.

By design, the notification composer in the firebase console is used to send notification messages using powerful built-in analytics to all devices. Now when it comes to sending user-specific alerts, this would require the device fcm registration token in addition to the notification title, notification body and notification image(optional).

For Production apps, the backend app server most of the time initiates the push notification by integrating the FCM REST API. For this to work, the mobile app has to send the fcm registration token for each device to the database server when the user is authenticated. Also when integrating push notification it is important to ensure that the app takes into consideration a way to register and unregister users from receiving notifications. FCM handles that through Topics that allow a device to subscribe and unsubscribe from notification messages.

FCM in Use: How to integrate push Notification in your flutter app

Now that we have a clear understanding of what Firebase Cloud Messaging entails, let’s see how to integrate push notification in a firebase login authentication app. We will first of all send push notification using Firebase Notification composer then we will make use of FCM REST API within the sample app to send a push notification message immediately after a successful login.

To follow up with the integration, check out the starter project on GitHub

Shall we?

Basic Setup

First of all, Open the Firebase console and navigate to the Project settings. Click on cloud messaging and click on the 3 dots in legacy option then select manage api in Google cloud console, then click on the button to enable the fcm rest api.

Once you enable cloud messaging api, it automatically provides you with a server key. This comes in handy with the device token key when sending notification messages through the FCM REST API.

Now that we have that setup, let’s go back to the app to add the basic fundamental dependencies.

The first step is to add the Firebase dependency that is responsible for connecting the flutter app to your firebase project. This has been included in the starter project pubspec.yaml.

The FlutterFire CLI is also a useful tool that provides commands to help ease the creation of a firebase project and seamless integration in your flutter app.

Next, within the top main-level function in our flutter app initialize the firebase app. This has also been included in the starter project pubspec.yaml

Next, is to add the firebase_messaging package as a dependency to your pubspec.yaml. This is the main plugin that handles push notification

Then we instantiate Firebase Messaging within the top main-level function

Next, add the flutter_local_notifications package as a dependency to your pubspec.yaml. This is used to create a Notification Channel to show pop-up notifications

Lastly we need to add the http package that handles calling the fcm rest api endpoint

Firebase Cloud Messaging Integration for Android

When it comes to setting up FCM client app for Android platforms we need to add the following to the AndroidManifest file inside the res directory within the manifest tag

First we need to add the internet permission outside the application tag

Next, it is always recommended to set default values to customize the appearance of your push notification on android devices. You can add the custom icon for the push notification within the application tag just before the activity tag. This is used when no icon is set for the incoming notification messages.

For us to add the custom icon we need to add the different resolutions within the drawable directory for the icon image. You can do this easily using Roman’s Notification Icon Generator but ensure the icon image that is used has a transparent background

Next, we add the custom color for the push notification also within the application tag just before the activity tag. This is used when no color is set for the incoming notification messages.

For us to add the custom color, we need to create a colors.xml file within the values directory in the res directory and add the following to specify the hex color code to be used.

Now to enable a click event for each push notification and FirebaseMessagingService we need to add the following within the application tag as well

Lastly, to effectively send push notification on android we need to define the notification channel id. This helps to define the identity of each mobile devices. To learn more visit the FCM Docs

To define the channel id, add the following meta-data tag within the application tag

For us to add the channel id, we need to create a strings.xml file within the values directory and add the following to specify the name of the channel id to be used.

Firebase Cloud Messaging Integration for IOS

Now we have to setup FCM client app for Apple platforms and we’ll have to make use of Firebase Cloud Messaging APNs interface to receive notification.

The first step is to upload your APNs authentication key from your developer apple account to Firebase. If you don’t already have an APNs authentication key, make sure to create one in the Apple Developer Member Center.

Within the project settings in Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab.

Under the iOS app configuration in APNs authentication key section, click the Upload button.

Then Browse to the location where you saved your key and select it. Also add the key ID and team ID which is available within the Apple Developer Member Center and click Upload.

For more information visit the FCM Docs for iOS platforms.

Send Push Notification from Firebase Notification Composer

Now that we have done the basic setup let’s test the push notification from the Firebase console using the Notification Composer.

To send a notification, go to the Release & Monitor section in the side panel of the console and click on ‘Cloud Messaging’. Then click on the button to ‘Create your first campaign’ and select push notifications.

Next, create a simple push notification by adding the Notification title, Notification body text and the Notification image which is optional. When the notification is created it displays on all mobile devices where the app has been installed.

Handle User permission and Device Token

Now that we have tested push notification from the firebase notification composer, it’s time to integrate the required functionalities for push notification with fcm. To achieve that we need to get the user device token and handle user permission specifically for iOS devices

First we have to create a dart file within the services directory and add a class named PushNotificationService

Then we create an instance of FirebaseMessaging and FlutterLocalNotificationsPlugin within the class.

Next, add an initialize function to define all the required push notification functionalities

Then call the function within the top main-level function of the app

Great, now for iOS we have to handle user permission before calling the push notification functions. We do this by making use of the FirebaseMessaging instance to request permission within the initialize function of the PushNotificationService class

Next step is to get the user device token within the initialize function. If this is successful then it shows that the device is connected to the Firebase console.

Handle Push Notifications when app is in Background

A user can receive push notification on their mobile device either when the app is open and in use or when the app is open but in the background. Let’s take a look at how to enable push notification when the app is in the background.

For us to do that we have to trigger Firebase Background Messaging to get the initial push notification messages when the app is in the background and the app is terminated. This happens within the top main-level function of the app.

The next is to handle push notification messages when your app is in the background and not terminated. This is done by listening to the onMessageOpenedApp stream within the initialize function of the PushNotificationService class.

To handle routing to a specific UI in the app when the user clicks on the pop-up notification, we make use of the data property received from the response of the fcm rest api which defines the type of view to navigate to. By default Firebase handles the push notification when the app is in background so a Notification channel is not required.

Handle Push Notifications when app is in Foreground

Now that we’ve seen how to handle push notification when the app is in background, let’s look at how to handle push notification when the app is in open and in use (foreground).

To enable foreground notification for iOS we simply have to call the setForegroundNotificationPresentationOptions method with the required named arguments.

Then to enable foreground notification for android while your application is open and in use, we need to listen to onMessage stream.

Routing to a specific UI in the app when the user clicks on the notification can be achieved through the onDidReceiveNotificationResponse callback function from the flutterLocalNotificationsPlugin instance. First we define both the Android and iOS initializationSettings within the . You can also specify the icon to be displayed for android notifications.

By default Firebase doesn’t handle push notification when the app is in foreground so a Notification channel is required to display push notification within the onMessage.listen stream. We make use of flutterLocalNotificationsPlugin.show method from the flutter_local_notifications package to display the notification. This is done by specifiying the androidPlatformChannelSpecifics that consist of the channel id, description and other pertinent details in addition to the iOSChannelSpecifics.

Send push notification using fcm rest api in the sample app

Now the moment of truth, let’s call the fcm rest api in our sample flutter app. What we intend to achieve is to send a push notification when a user is successfully authenticated. Then when a user initiates a click action it routes to a ui view specified in the data payload. Firebase provides us with a url to send notifications as a post request with a compulsory payload that defines the attributes of the notification.

First of all, within the services directory create a dart file and add a class named FcmService that handles sending a post request through the fcm rest api url

Next within the FcmService, create a variable to store both the server key which is automatically displayed when you enable cloud messaging api on firebase console, then the device token key which we’ve gotten and the fcm rest api url. Kindly note that it is advisable to store these sensitive data in a .env file

Now we need to specify the headers that will be passed while calling the FCM REST API url. One of which is the server key that provides access to send push notification to users device.

Then we also need to specify the data payload that will be passed alongside the headers. This is where we identify the user device token, data response, notification title and body text.

  • The value passed to the to field is the device token.
  • While the values passed to the notification field is what is displayed on the push notification. This includes the notification title and body text.
  • Then the values passed to the data field is used to handle routing to a ui view when a user clicks on the notification.

Next step is to create the method that sends push notification within the class named FcmService. Then we call the fc rest api url passing the required headers and body payload as a POST request.

Great, you are one step away from integrating push notification in your sample flutter app. The last step is to call the sendPushNotification method within the login viewmodel, then we check using the model response if it was successful or not.

Send push notification to multiple devices

To send notification to multiple devices we need to subscribe a group of devices to a topic then target the topic name while sending push notification. It is advisable to allow a device subscribe and unsubscribe from topics which refer to receiving notification messages or not.

Here is a sample json to send push notification to multiple devices

Testing our sample app

Great, we have successfully integrated push notification in our sample flutter app. In order to confirm the validity of the implementation we need to login with a valid credential from firebase. Once the authentication is successful a push notification is displayed on the users device from the FCM REST API.

Notice that when the user was successfully authenticated a push notification message was sent to the user almost immediately. Then when the user initiates a click action it routes to the home view instantly.

Conclusion

In this article, you were introduced to Firebase Cloud Messaging and it’s REST API, the benefits and how to easily integrate push notifications in your flutter mobile app using a sample firebase login authentication app.

Push notifications are essential tools for mobile developers who want to increase user engagement and retention in their apps. By using Firebase Cloud Messaging, developers can ensure that users stay informed and engaged with their app. Thanks for reading.

Check out the complete source code for the sample app. If you have any questions or inquiries, feel free to reach out to me on Twitter: @CalebJ or LinkedIn: @Caleb

--

--

Caleb Jesusegun

Mobile Engineer | Product Designer | Technical Writer | Blockchain Enthusiast