How to handle background push notifications in Flutter š
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 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.š
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šš½