Flutter Push Notification with Firebase Cloud Messaging (FCM) and Routing to Specific Screen

Ken Lee Chiaw Huat
9 min readJul 22, 2019

--

For this topic, I will cover the initial step such as what are the configurations and code that needed to be put in place in your Flutter project as well as steps needed on the Firebase dashboard. Then, we will proceed with the coding part on Flutter focusing on Android platform on how to receive message from FCM. We will then make additional code and changes to test on how we can navigate to different screen on Flutter app based on the content of the message received from the FCM.

In real world system, most of the time there is a backend system that running to support the front end app. This include pushing specific data that contains info that require the front end system to display in the right section of the app.

Let’s start by creating a new flutter project.

Setting up FCM dependency on Flutter project

In your pubspec.yaml file, you will need to add the firebase_messaging dependency for FCM as below:

Then, get the package. As I’m using Android Studio, this can be easily done by clicking the pop-out upon adding the above dependency.

Assuming no error, proceed to the next step.

Your version of firebase_messaging may be different; you can double check this at firebase_messaging library at pub.dev — Dart packages location.

Setting up Firebase for Android

First, assuming we don’t have a Firebase project created, go to Firebase Console. Create a new project.

Enter the name of your project, and follow the screen guide to complete this step.

You should see a similar screen as below once the project has been successfully created.

Next, we will proceed to the Grow section (left navigation), expand it, look for Cloud Messaging. Click on the Android symbol that appear (refer below — circled in red).

Upon clicking the Android icon, the following screen will appear. You are required to provide the Android package name.

For the Android package name, you need to go back to your Flutter project, look for AndroidManifest.xml located at your project folder android/app/src/main. Open it, look for package and copy the value into the Firebase Android package name. Once done, click on the Register app button at the bottom of the screen.

Next, click on the ‘Download config file’ which you need to download the google-services.json and put into your project android/app folder.

Once done, back to the Firebase dashboard, click on Next. You need to follow the additional steps to add Firebase SDK to your project gradle files.

First is the project level build gradle file located <project>/android/build.gradle where we need to add the google services class path.

This follow by app level build gradle file located at <project>/android/app/build.gradle where we need to apply the plugin for google services we added earlier.

Next is to add the following <intent-filter> within activity tag to your <project>/android/app/src/main/AndroidManifest.xml. Add the following:

Sample of updated AndroidManifest.xml file:

And that is all needed for the configuration part for both project folder and Firebase side. Next is to the coding part.

Take note, the above steps are only for Android. Unfortunately, I do have an Apple ID, thus focus area is only for Android.

Now we are ready for the code part. The end result of the UI will look like this:

It will contain 2 bottom navigation bar items, in which the 2nd item called Notifications will contain a red color indicator when there is new push message received when the app is in foreground.

First, we create the main class. In my case, I called it PushMessagingExample class, which is a StatefulWidget type. For convenient, all classes created will be inner class inside the main.dart.

When the app is being launch, there is possibility the initial frame to get the token is empty. Hence, I putting a temporary text stored in _homeScreenText that will be used to display at the main screen.

As we will be having bottom navigation bar, I want to make sure that when there is new message from FCM, it will update the ‘Notifications’ item with a red color indicator. When user click on it, it will reset it back (and the red color indicator is gone). To do that, I will add this integer called _bottomNavBarSelectedIndex that will be used in the later code.

The boolean _newNotification is needed to display the red indicator on the Notifications icon when there is new FCM when the app is in foreground.

Last, the most important for this FirebaseMessaging — create an instance of it.

Next, we will need to override the initState method.

The first part ‘_firebaseMessaging.configure…’ is needed. Here is where we can provide the code structure when the app received FCM message, how it should handle — when the app is in foreground, onMessage will be called. When the app is in background, onResume will be called and when the app is not in both foreground or background, onLaunch will be called.

As for iOS, there is additional code we need to put in place. Although I did mention in the beginning of this article, this is more for Android platform, I will just leave the code here — for future reference.

The getToken() method is optional, however is good to know that there is a method available to get the token — for this example, I will be getting it and display on the man screen.

The method _navigateToItemDetail as per the name hinted, is to convert the message return from FCM and then route it to the specific detail page on our app.

Now, there is a sub method called _itemForMessage which is specifically handling the conversion of the raw message from FCM to our local dart model/bean.

Create the inner class MessageBean and another method called _itemForMessage such as below:

Next, we will need to create the detail page that going to display the content of the FCM message. Here, we called it DetailPage and it is also a StatefulWidget class.

The final piece of the code section is we need to update the build method for the main class PushMessagingExampleState that contains the UI code to display the token, bottom navigation bar and the conditional expression code checking to handle the Notifications icon to show or not an indicator of new message arriving from FCM when the app is still in the foreground.

As the code is too long, refer to the GitHub link here.

Take note, to link the runApp with this class.

Now we are fully ready for testing. Switch to your Firebase dashboard, go to Grow -> Cloud Messaging, click on the ‘Send your first message’ button located at the center top.

Once clicked, you will reach the ‘Compose notification’ page. Provide some testing notification title and text message that you plan to send out to your Flutter app.

At the ‘Target’ section, under the user segment, select the package of the Flutter project that we just created.

Just click Next once one, however, at the ‘Additional options’ section, you need to provide the following:

Notice the custom data, we added the key-value pair of id, status, status and click_action.

The first 2 fields namely id and status is mainly data needed for our testing. As I mentioned earlier, we want to direct user to specific section and post — thus we need some unique identifier such as id and status. You can consider id as the primary key of the message and status is like an indicator to inform the app which section/page this id is for. For this example, the data is for Crime_And_Safety section with id of 2.

FLUTTER_NOTIFICATION_CLICK which is something we all have to do. That note, this value must match what you specified in AndroidManifest file.

Save it as draft first. We will move to the Android Studio and run the app first. You can run it in emulator or at the phone, no issue.

If there is no error upon running your app, you should be seeing the main screen as below.

We going to test few scenarios. For the first 1, lets test with when the app is running in the foreground. Back to your Firebase console, duplicate the same notification up to 4 as below:

Once done, while the app is still running in the foreground, mouse over to 1 of the draft notification is the list, expand the it and click on Edit notification.

Once clicked, click on the Review and then follow by Publish. Now, in your app, you will notice the Notifications icon is now change and contains a red indicator.

So, it works as the code we added earlier is to update the bottom navigation bar item to contains this red stack when there is a new FCM message coming in.

Click on the icon and it should reset it back to default view. Actual scenario is, when you click on the notification list, it should route you to a different page. But, we will not cover it here.

Next, click the Home icon on your emulator or your Android phone which will result the app going into background.

To test the next scenario, we will push another draft notification and we should be receiving it as well.

Of course, when you single click on it, it should bring back the app to the foreground. Also, it should route you to the detail page of the app.

Now, if you kill the app and run another push notification, it should work too. The same behavior as above where the app will be launch, and then route to the detail page.

That is all, for the complete source code, please refer here.

Thanks and I hope this can be useful for someone out there that want to find a working example of just receiving notification from FCM, but routing to the specific page based on the data receive.

--

--

Ken Lee Chiaw Huat

Technical Blogger | Mobile Developer@Flutter | Software Consultant | Father | Entrepreneur