How to handle background push notifications in Flutter šŸ””

Osama Asif
3 min readMar 24, 2021

Recently I was working on notifications. While implementing it I faced an issue that Iā€™m not receiving notification in the background and also when my application got terminate. I searched a lot and I saw that Itā€™s not only me whoā€™s facing this issue the Stack Overflow and GitHub are full with this issue. I did a lot of research on it and finally, I overcome this issue.

So Letā€™s start

STEP # 1

First Import all the necessary plugins.

Here Iā€™m using these versionsšŸ‘‡

firebase_core: ^0.5.3

firebase_messaging: ^7.0.3

flutter_local_notifications: ^4.0.1+2

STEP # 2

Setting up the AndroidManifest.xmlšŸ‘‡

šŸ‘ˆ File Directory

Add this line Inside your main activity after android.intent.action.MAIN

Add this MetaData outside of the main activity.

šŸ‘ˆPlace your Icon here for the notification

STEP # 3

Create a file called firebase_service.dart and create an instance of flutter local notification and firebase messaging

STEP # 4

Now in firebase_service.dart create a function called setupFirebaseAndLocalNotification.

Now take a look at whatā€™s happening inside of this function.

Now call this function in your main.dart main functionāœŒļø

Here at very first, Iā€™m initializing the flutter local notification with android and ios configuration and along with that Iā€™m giving the notification icon in android settingsšŸ‘‰ AndroidInitializationSettings(ā€˜notification_icon_pushā€™)

STEP # 5

Create a function called myBackgroundMessageHandler

So this is my function for handling the background notification here you can do whatever you want to do like navigating to the specific screen etc itā€™s up to you.šŸ§ 

STEP # 6

NOTE:- You can never hit the background notification if you send the notification from the firebase console so in this you have to create a postman request.

The background notification handler depends on the payload so be careful here. Iā€™m sharing the sample request to do it right.šŸ‘ˆ

Post request URL šŸ‘‰ https://fcm.googleapis.com/fcm/send

for sending the notification you have to add the server key in your request headeršŸ‘

Now hit the send button and check the notification in your mobile app.šŸŽ‰

Here you can check the payload in your background handler.

For a real quick implementation copy and paste the below code in firebase_service.dart and follow the rest of the stepsšŸ„±

Hurrayā€¦!!!šŸ„³šŸ„³šŸ„³

So these are the basic steps to get notifications in the background. Support me by giving claps and follow me if you like itšŸ™šŸ½

--

--

Osama Asif

Seasoned software engineer with over 6 years of extensive industry experience specializing in the development of mobile applications.