Technology

Smart Push Notifications with Flutter & FCM


When used correctly push notifications can be an extremely powerful way to drive user engagement but when used incorrectly they can do the exact opposite and drive users to uninstall your app luckily there’s a service called firebase cloud messaging that allows you to be smart about the way you broadcast notifications to your users

Take it from me be smart be safe in today’s video you’ll learn how to receive messages from a front-end flutter app and also how to broadcast them from a back-end cloud function we’ll look at how to broadcast notifications to a single device or user

To a topic or to a segment of your user base based on the analytics data that you collect by the end of this video you’ll be able to combine these techniques together to create a sophisticated pipeline for app notifications if you’re new here like and subscribe and you can find the full

Source code on fire ship IO and congrats to mateo Petrovich your last week’s t-shirt winner but there will be another giveaway with this video all you have to do is leave a comment below now before we get into the actual source code let’s talk about the three main ways that you

Can send push notifications with firebase Cloud messaging the most broad approach is to send a notification to a segment of your users this could be as broad as all the users for your Android app but typically you’re going to drill down to a smaller audience for example

You might want to target all of your Korean Android users whose last app engagement was more than ten days ago and that will tell you exactly how many users will receive this notification as well as their relative size to the total user base on top of that you can use

Firebase predictions to dynamically segment your users and send notifications based on the type of engagement you’re trying to get and that means you can just fire the UX person who’s in charge of doing this manually and like google’s AI handle it what are you getting fire me

No I already why are you still here another option is to manually subscribe a user to a notification topic this is useful if you want a user to opt into a certain topic or if you want to programmatically assign them to a topic in the background of your app for

Example a user might follow a certain category like puppies so you want to subscribe them to puppy notifications in the third and most personalized way to send notifications is to send them to a single device or user and you can do that because every device that you have

Permission to send notifications to will give you a token a token itself is just a string that identifies the device and in a few minutes we’ll look at how we can save these tokens to firestore and associate them with a user and that makes it possible to send notifications based on individual user

Activities now as we’ll see in this video the actual sending of notifications can either be done on the firebase console or you can do it programmatically with a cloud function in most real-world applications you’ll be doing most of the notification sending with a cloud function especially if you’re sending to

Individual device tokens now that you know a little bit about firebase cloud messaging let’s go ahead and jump into a flutter app that has already been configured with firebase for both iOS and Android on Android there’s only one additional optional step to setup push notifications you just need to add this

Intent filter to your Android manifest file on iOS there are a few more steps involved because you need to register a certificate with the Apple push notification service there’s already a detailed official guide for this so I’ll go ahead and link to that in the video description the next thing we’ll take a

Look at is the pub spec Yamma file and you can see here we have firebase core auth cloud fire store and messaging now if we go into the main dart file you’ll see here that I’m importing dart io so we can do platform checking and we’ll also import our firebase services now

Typically I try to keep the business logic separated from the UI logic but this is a situation where our logic is pretty tightly coupled together and I think it makes the most sense to handle everything in a single stateful widget so this message handler widget will take

Care of getting permission from the user saving the device token to the database if necessary and displaying the actual UI elements when a notification is received now the first thing that we want to focus on is the UI and there are three different callbacks that you need

To know about the on message callback will typically be called when the app is running in the foreground that means the user is actively using the app when the message is received then you have the onresume callback which will be called when the app is running in the

Background and the user clicks on the notification from the actual device and the third callback on launch will run if the user clicks on the notification but the app is completely terminated and needs to reboot now when it comes to Android you need to set the click action

To flutter notification click to use the background or terminated callbacks and we’ll look at exactly how to do that when we get to the cloud functions now the only callback that we care to implement for this demo is on message when the app is in the foreground and we

Can use one of flutters built-in widgets like a snack bar or an alert dialog the snack bar approach is a lot more subtle because it just they bar down at the bottom and will be automatically dismissed if the user doesn’t engage with it but if you have a really important message that should

Interrupt the current experience then you can use an alert dialog and that will force the user to manually dismiss the message inside of an it state will call FCM configure to set up the callbacks that will handle the message when it’s received by the device and

Each one of these callbacks will give us access to the actual notification data payload to display a snack bar we can first define the snack bar widget and then we’ll set the text to the notification title and you can optionally add an action here to go to a

Different screen when the user presses on the notification then to actually show it we call scaffold of context show snack bar which will look up the widget tree for the nearest scaffold and display it so that’s all we need for a snack bar if we want to show an alert

Dialog we can use the built in show dialog method and then define a builder that defines an alert dialog and we can pass that the notification title and the body and then we can dismiss the alert by simply calling navigator pop now we can also define the on launch and on

Resume callbacks or we can leave them blank which will just cause the app to be opened if a notification is clicked on in most cases you’ll probably want to navigate to a specific screen when the user clicks on a notification in the background at this point we actually

Have everything in place we need to start receiving notifications on the device as long as that device is Android on iOS you need to explicitly request permission from the user and that’s actually really easy to do we simply call FCM request notification permission and then pass in the iOS notification

Settings now if we go to the firebase console and send a notification to a segment it should be received by this device now the next thing we might want to do is subscribe the user to a specific topic you can subscribe or unsubscribe from a topic with a single

Line of code you might do this entirely in the background or you might have a button that says subscribe to puppy notifications that the user clicks and now they’re subscribed to that topic of notifications and now if we want to send a notification to all devices subscribe

To that topic we can do so in the firebase console or with a cloud function but what if we want to send notifications to an individual user or device to make that happen we’ll need to retrieve the fcm token from this device and then save it in a back-end database

Somewhere like firestore before we implement the code let’s start by looking at the actual database model we have a user’s collection that contains some information about a user profile and under that we have a sub collection called tokens and each document in this collection represents a device token

That the user has given us permission to send notifications to and a token is nothing more than a unique string so we can use the actual device token as the document ID in the sub collection and that just makes it easy to enforce uniqueness for each document in this

Collection now getting back to our flutter code the next thing we’ll do is implement a method called save device token and I’m just referencing a mock user ID but in a real app you would most likely await the auth current user after you’ve already logged a user into your

App from there we can retrieve the FCM token from the device by calling get token and then we’ll make a reference to that token subcollection under the user that uses the FCM token itself as the document ID and then we can also save some optional information here if we

Want like a created at time stamp or the platform operating system from there we’ll go back to our an it state lifecycle hook on this widget and on Android we can simply run this code when the widget is initialized because the token should already be available but on

IOS we need to make sure that the user has actually finished giving us permission so we’ll go ahead and listen to the stream and then once we have data then we’ll go ahead and save the device token now go ahead and restart your flutter app and you should see the

Device token being saved a firestore when you fire it up and you can go ahead and copy that token and bring it over to the FCM screen and you can send a notification directly to this device so that takes care of all of our front-end code but now the question becomes how do

We dynamically send notifications to a user based on their actual activity in this app and the best answer to that question is firebase cloud functions although you can use any of the firebase tab and SDKs to send messages go ahead and run firebase and it functions from

The root of your project and I would highly recommend using typescript as the language here and if you’re not an expert with typescript or JavaScript don’t worry because the implementation details for this code are really simple first we’ll go into the index TS file and import firebase admin initialize it

And then setup variables for fire store and FCM when it comes to sending notifications to a specific topic you’ll most likely do that when something changes in the database for example you might have a puppy’s collection and you want to notify everybody subscribe to the puppies topic when a new document is

Added to the database we can do that by setting up a cloud function that listens to the fire on create event in the puppies collection when a new document is created that’s going to give us access to the puppy data on that document and then we can create a notification

Payload with that data the cool thing about this is that we can use the data in the firestore document to customize the notification itself for example we’ll say puppy name is ready for adoption now there’s a lot of different ways you can customize the notification itself but the most important properties

Are the title body and icon because they dictate how it appears on the actual notification tray on the device and you’ll also want to set the click action to flutter notification click if you want to use those background callbacks that we looked at earlier and the final

Step is to simply send a notification which we can do by calling FCM send a topic along with the topic name and the notification payload and that’s all the code it takes to broadcast a notification out to potentially millions of devices that are subscribed to this puppy’s topic now let’s go ahead and

Write a second cloud function that will listen to the orders collection and then it will send out a notification to an individual user whenever they’ve received a new order when an order document is created we’ll assume that there is a price a product and then a user ID for whatever user sold that

Product in the cloud function we’ll go ahead and take that user ID to make a query to that tokens collection under the user ID that will give us a query that returns all the device tokens for a specific user now because each one of those documents uses the actual FCM

Token as its ID we can simply map the snapshots down to an array of the document IDs then we’ll go ahead and format the message payload just like we did in a previous example and then we’ll say FCM send to device with this array of tokens and that will send out a push

Notification to every device owned by this user now the final step is to deploy the functions then if we go into fire store and create a document it should broadcast the notification to our emulator or local device and we now have a full stack solution for a cloud messaging that can handle multiple

Paradigms of app notifications I’m gonna go ahead and wrap things up there if this video helped you please like and subscribe and consider becoming a pro member at fire ship IO to get access to the full footer firebase force thanks for watching and I will talk to you soon

#Smart #Push #Notifications #Flutter #FCM
For More Interesting Article Visit : https://mycyberbase.com/

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *