Flutter Firebase Push Notifications Tutorial | 2024

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone in this video we'll be learning how to push notifications inside our flutter application using filebase messaging and we will be also learning how we can save fcm token of specific device inside our fire stre since we are going to save the unique fcm token for each user we also need to identify which token belongs to which user for that reason we need authentication for authentication we are going to be using Firebase art this video consists of several parts first we'll be starting by adding five Bas authentication then we will continue to add five b notifications in all the three states foreground background and terminated State and then we'll learn how we can save fcm token inside our fire store so let's start this video first let us start by creating a simple application using flutter create command flutter create you can give it any name as you like now navigate to the folder and open it in vs Cod we will be adding several packages for that we need to add some dependencies here use flutter pu add Firebase messaging flutter local notifications Firebase code fire base or Cloud fires 2 click on enter and it will install all the dependencies for your project now once done you need to verify your pet. yl file that all dependencies are added correctly or not inside left folder create a new folder name it as views here we'll write the UI logic first for login page here we'll be creating a stateful widget for that use STFU and use the shortcut create a stateful widget give the name as login page and here we'll have a scaold instead of a placeholder remove the con scaffold here first we'll be having two text editing controllers one will be our email controller and other will be our password controller which we are going to be using to take the input from the user and for a text form pH inside scaold body will be having a center widget and Center will have a child of simple padding of 8 pixels padding will have a child of column and column will have main Access alignment. Center and crossx alment of start then we'll have some text with some basic text Tye a size box of 10 Again a text form field that will have the controller as email controller and label as again a size box of high1 and now up text editing controller of controller of password controller and then again a size box of height 10 and then a size box of with double do infinity and that will have a elevated button with text of login and then we'll be having a size box of height 10 and then we'll have a row that will have main access alignment of Center and cross access element also of Center the children will be first a simple text new account and then a text button of text register now this was our first login page UI here if we check main do. file currently it is running my homepage the default the default wiet that flutter creates while building an app since we will be dealing with routes so for that we'll not be using Home Instead we'll be using routes let the root route be our login page that we have recently created and here we will not be requiring default my homepage we can remove it one more thing we need to do inside Android folder app build. grle change to minimum SDK version to 21 and now let us test our app allow to install now this is how our basic login page looks like now similar to our login page let us also create another file for sign up name it as signup page. D and just copy to login PGI because it will be very much similar and here the name will be sign up page instead of login it will be sign up here everything will be similar the text will be different like already have an account and it will be login now add this inside our route it will be our signup route it will navigate to sign up page now it's okay now we need to link the navigation routes when the user press the register button the user should be navigated to our sign up page for that inside our login page when the user press the register button we will be using Navigator do push name and providing the name of the route sign up now if you Press Register here it is navigating us to the sign up page now this will be sign up not login just change it now if we press the login button it should redirect us back for that we can use Navigator poop context it will navigate us back now after login or sign up we need to show a homepage for that let's create a homepage it will also be a stateful wiet name it as homepage here we'll be having a scaffold and let's give it a Aba we'll have a APPA widget of title text home and in our actions we'll be having an icon button on this we will do nothing for now and icon will be icons. logout now we have almost bu uis now let us work on the authentication part first first we need to visit our Firebase console here we can either create a new project or use an existing project in my case I'm creating a new project give it name save token Firebase click on continue disable Google analytics for now we don't need it create project now click on continue here we need to add our flutter app for that we need to have fireb CLI installed if you don't have Firebase CLI installed then you can either download the exe or install it via npm by simple running this command for this you need to have node and npm installed in new system now let us start by doing five Bas login so here we need to open our terminal and you use Firebase login click on Y and it will ask you to authenticate with your account click with the desired account you want now allow it now our login is successful now we can move to the next step here we can run this command now past this and after that also run this command now our fireb CLI had added a Firebase options. dot file now what we need to do here here inside our main do dot we need to First make this function async and after that use widget flter binding do andure initialized and then initialize our Firebase app we need to import Firebase from Firebase code. do and also default Firebase options from Firebase options. file that our Firebase CLI has created now pause now stop the app and rerun it again now our app is running we are having no problems here we'll be creating holder name it as controllers here will will be creating a new file let's name it as OD service do do here we'll be creating a class name it as OD service here we'll be writing our first function for creating a new account let us create a static future return type of string function Name It We are naming it as create account with email here we are going to expect email and password parameters to be passed to this this function it will be an async function and here we'll use try catch to handle any exceptions here we'll be using fb. instance. create user with email and password for email we'll be providing the email that we are accepting and password the password that we are expecting and after our account is created we'll be returning account created and on Firebase a exception will be returning the error message to string and in case of any other exception we'll just return that error to string for this we need to import Firebase or just import the package firebase. now this was our account creating function now let's write the function for login similar to our sign up we are going to be writing the function for login the user with email password method so for that we are going to create a static future return type of string function naming naming it as login with email here also we are going to expect the user to pass email and password it will be an async function then using try catch first will be using Firebase do instance do sign in with email password provide the email and password then we will will return login successful if everything happens correctly otherwise in case of exception we are going to return the error message to string and in case of any other exception we are going to catch it and return that error to string for logging out we are going to be simply using a static log out function that will call fireb instant. sign out and it will log out the user from the device and we also need a function to check whether the user is signed in or not for that let's create another static is loged in function that will call Firebase instance. current user and then we'll check if the user is not equal to null so if the user is not equal to null it means that the user is log them it will return true otherwise it will return false now we have written all the functions for our authentication now we need to link this function with our UI now we need to link our homepage with our routes so here we'll be having slome it will be our homepage here will be creating a stateful widget let's name it as check user here inside our init state will'll be using service do is loged in so it will provide us a value either true or false then the value that will receive if it's value means it is true in that case we will navigate the user to the Home Route using Navigator push replacement is will'll navigate the user to the login page now here instead of our root rout here for our root route will not have login page instead we'll have check user page and for our login page we'll have login route here will have a stold and body will have a center child will be circular progress indicator now if we restart application you'll find a circular progress indicator for a very short period of time we need to visit our Firebase console from here we need to select authentication here we need to provide a signin method click on setup signin method we will be only requiring email password method for now click on email password and enable email password method we don't need passwordless sign for now click on Save now our email password method has been enabled inside our signup page. file we need to make this onpressed function async and then we will await call the class or service do create account with email the function that we have created and pass the email controller. text and password controller. text and after that we'll be getting a value in return type of string so if there is a value if the value of string is equal to account created it means everything has worked correctly and account has been created in that case we'll be showing us snag bar of account created and after that we'll be redirecting the user to homepage us using Navigator push named and remove until to our home route now here we are using Navigator do push named and remove until CU if a new user sign up we are first showing the login page then they sign up and if they register then we are navigating the user to the homepage if we use Navigator do push replacement in that case sign up gets removed but login still stays on stack now if the user press back button from the homepage then they will be sent back to the login page in that case it will not be a correct thing for that reason we are using Navigator push named and remove until else will show an error snapa of colors. red. shade 400 it will show the error message now let's try to sign up so now here we are getting redirected to our home page and it's also showing a snack bar of account created let's verify with our users here as you can see that our account is also getting created inside our homepage when the user press this icon button of log out we need to make this onpressed function async and then we need to use await or service. logout function that we have created and after that we will be navigating back our user to the login page using Navigator do push replacement name to our login route we need to also import OD service now if we restart you'll find that we are getting redirected to the homepage directly now if we log out we are getting redirected to the login page now if you restart we are getting redirected to the login page it means that check user is working correctly now let us work on the login page here when we press the on press button on press first we'll make this ASN and then we will use await use OD service do login with email function that we have created and pass the email controller. text and password controller. text then we be getting some value in response in form of string if the value is equal to login successful it means that everything was correct and now we can redirect the user to the homepage first we'll show a snag bar of login successful and then we'll use Navigator push replacement to redict the user to the homepage this will show the error message with a snack bar of colors. red. shade 400 background color so now let's try to log in so now here we are getting login successful and we are getting redirected to our homepage now also test with errors let's try to enter some wrong email and wrong password so here we are also getting the error message now our authentication path is done now we can focus on the notification adding part now we have already added the necessary packages that we will be requiring for receiving notifications like flutter local notification file based messaging now we need to ask the permissions for the Android device so for that visit Android app SRC main here you will find Android manifest.xml file click here now we need to add some permissions first two permissions are for internet access then next for receiving boot completed and vibration and full screen intent and exact alarm permissions and also post notifications permission for Android 13 in a now just save it now we need to create another file name it as notification service do do here we need to create a class name name it as push notifications you will creating here will be creating a static final five Bas messaging variable and we'll initialize it to fireb messaging. instance and then we'll have then we'll be creating another static final variable of flutter local notifications plugin name it asore flutter local notifications plugin and initialize it to FL a local notifications plugin now we need to import this plugins Firebase messaging and pl of local notifications to request notification permissions and then create a static future init function make it async and and uh we'll use aore fire messaging. request permission and here we are going to be providing all the properties and after requesting the permission now we can get our device token so let's use final aore fire dis messaging doget token and we are storing it in a variable called naming as token now we can print our token in this case it will print our FM token now for receiving notifications in our foreground State we need to uh we have to use flutter local notifications to show the notifications for that let's create a function to initialize local notifications name the function as static future local not in it you can name it anything make it async then we need to use Android initialization settings here we mainly need to provide the app icon or the icon that the notification will have then Darwin settings for iOS and Linux settings for Linux then we need to use initialization settings and specify all the initialization settings that we have declared and then we need to request permissions for Android 33 and this is a new thing so use uncore flutter local notifications plugin do resolve platform specific implementation and here we need to call it do request notifications permission it will request post notifications permission for Android 30 an ER the permission that we have declared inside our Android manifest.xml and then we need to call flutter local notifications plugin. initialize for initializing the notifications with initialization settings here we need to pass our initialization settings and it also expect us two functions did rece receive notifications and did receive background notifications we can create a simple on notification tab function for both of them like this when the user tabs on notification in foreground here to handle this we are creating a new function on notification tab and here we expect uh to pass notification response for now we don't need to do anything now if we call this local noty in it it will initialize local notifications now we need to call this init and local init functions to initialize local notifications and Firebase messaging inside our main. DAT file before running our application so here inside our void me a in function we will be writing the we'll be calling await push notifications. init to initialize Firebase messaging and await push notifications. local in it to initialize local notifications it will ask for notifications permissions and then it will generate aim token for us now let's stop this application and try to it again now after initializing it it's providing us the fcm token here this is the fcm token for this device for our easy navigation from one route to another we'll be creating a navigator key a variable Navigator key and assign it to Global key of Navigator State and now inside our material app we can pass Navigator key as the Navigator key that we have created we can uh take the help of Navigator key to navigate the user from one rout to another now we need to also create a very simple message screen for that inside views we'll create a message do do file and here we'll be creating a stateful widget message it will be a scaffold for abar we'll be having a simple AAR of title text your message you will be having a map of payload when we redirect the user from any screen to the message screen in that case we need to pass some data for that we'll be creating a new variable data and we will catch the data in form of model route. off context do settings. arguments and here we'll be getting the data now we'll be getting the data of two types first one as a return type of remote message and second one is of notification response now for our background and terminated State we'll be getting it in form of remote message so the data will be in form of Json we don't need to decod it and St the Json data that we are getting inside our payload so for foreground State we need to check if the data is of notification response then we need to decode it to Json type so for that we'll use Json decode and decode the data. payload that is coming from our flutter local notifications and we need to import this packages for remote messages local notification response and Jason Deco now our data is now available inside our payload in that case we can show the P inside Center child text P do string now it will show the payload that we are receiving from the notification and also here we need to add the route or as message context it will be our message screen for our background notifications we need to create a function that will listen to background notification changes function to listen to background changes so we are naming the function asore fire background message and we are expecting to pass remote message make it async if there is any message in that case we're just printing we are just printing some notifications received in background now we have created this function outside the main function now inside our main function after both of our initialization are done we need to listen to background notifications using Firebase do on background message and it accepts as a future function of remote message Handler to be passed so for uh here we can pass this undor 5 P background message function that we have created now it will listen to any background message that we receive inside our Android manifest.xml file after Ed just resize just add this three more activity and here we need to visit Firebase engage and select messaging here we need to create our first campaign as Firebase notifications now just this is this is a test notification test app and then we can send a test message here we need to provide the ab token so use this token our device token now let's test it now here we are getting the notification run our app in background and then send the test notification here we are getting a test notification and it's also showing some notifications received in background means the function that we have created is getting called after we are receiving a background notification now if the user Taps on the background message we want it to open on the message page instead of the default homepage so what we are going to do we are going to create we are going to be using Firebase do on message open app and there we are going to listen here we'll be getting a response of remote message so we are using the variable message and then if message. notification is not equal to null it means that there is some notification in that case we'll be first printing background notification tab and then we'll be using Navigator key do current state add a null check and then push named here we need to provide the name of the route it will be our message route this route that we have created and then here inside our message route we are also expecting us the payload of message to be passed in form of model route so we'll be also passing the arguments and here we'll pass the remote message below that it's coming from Firebase background message now let's save it now if we try to click it for now it's Opening Our homepage cuz it's not CU it didn't get reflected now let's try to stop our app and rerun it again now again make our app in background and send a test message this time we will also send the payload key as hello and value as world and here notification click on send a test message use the same if s token now we are receiving a background message click on here now it's it's redirecting us to the message route and it's also showing us the payload that we have passed now for showing notifications in our foreground State we need to use local notifications and with the help of that we are going to show simple notification so first here we are going to write the function to show a simple not ification using local notifications create a static future show simple notifications function here we are going to expect title body and the payload make it asent and here const Android notification details create a new variable Android notification details and there we need to initialize it by providing a channel ID channel name Channel description importance level to importance. Max and priority to priority. high and then a ticker naming a ticker and then we'll create a notification details variable of notification details there will provide the Andro notification details that we have created just a now we'll use await flutter local notifications. show here we need to provide the ID title body notification details and the payload so let us provide a ID title body notification details and the payload this title body and payload we are expecting it to be passed by calling this function and notification details is how we are initi izing the Android notification details now if we call this function it will simply create and show a simple notification in our foreground State now if we tap on the notification on foreground state in that case we are not doing anything we can use Navigator do current state. push name and here we uh need to provide the name of r that this message and in our arguments we'll provide the notification response now in our message UI we have already written the code for handling notification response arguments we need to import this Navigator key that we have written in our main. file now if the user press the notification in the foreground state it will redict to the message page and show the payload now we we need to also link it with our main do. file now for handling now we need to call this show notification function now we need to listen to the notifications when in our foreground state for that inside our main. do file now here we can create the logic to handle program notification is first we'll use Firebase Doon message. lesson and here we'll be getting remote message here we are creating a string payload data you will encode the message. data means the payload that is coming from the remote message and then we will print got a messaging program if the message. notification is not equal to n it means that we have received some notification in that case we'll use push notification. show simple notification and we need to provide title body and payload the title will be message. notification null check. title null Che and body will be message. notification. body and for payload we need to pass the Json encode payload data that we are creat here we need to import Json incode from that. convert now if you run our application now our app is in foreground State now let us send a notification from here now here it's showing this is a test notification when we click here it is redirecting to the message page and also showing the payload that we have passed it means that we are also able to handle the notification in foreground State now for handling notifications and terminated State we need to create a new variable of return type of remote message we are using question mark because the value may be available or may not be available for that here we are creating a variable message and here we will use await Firebase messaging do instance do get initial message and here if our message is not equal to null it means that we have received some message and then we'll print launched from terminated State then we'll wait for some time and then use future. delay for 1 second and then we will navigate the user to the message page passing the message as arguments so now let's save it now it would be better to stop the application and uninstall the app and build the app again install it now if s token will change this is our fcm new fcm token just copy it for test message add this new epsin token now here currently this app is running in background now if we remove this we lost the connection now let's try to send a test message you'll find that we are getting the notification currently the app is in terminated state if we click on this notification it is redirecting us to the message page and it's also showing us the payload now if we click back it's taking us to the login page so it means that we have successfully added the functionality to deal with notifications and Terminator State now for all three states foreground background and terminated State notifications are working now let's move on and start saving the device fcm token to the fire store database in our case we are selecting fir store database but it has no limit you can choose any database depending on your need now here in Firebase console visit build your select fire store database you're going to create a database you just choose the nearest location and for now let's keep it for test mode now our PR database has been created we need to visit rules and currently we are allowing read and write if the request time is less than this time stram but this is not so good we can modify this and add a new rule if request do is not equal to null it means the user should be authenticated for reading and writing inside our fir store database now we can publish this for saving the device fcm token inside Firebase fire St we need to create a new file name it as gri service do d now here we'll be creating a class of C service and inside that we'll have a static user variable of return type of Firebase user will assign Firebase c. instance. current user now here we'll write the logic for saving our fcm token to fire St make a static future function name it as save user token it will expect us to pass a token of typ string make it easy here we are creating a map of string and dynamic naming it as data and here will here we are going to use a key of email and store the current user email and a key of token that we are going to use to store the fcm device token and this way we are creating a map of data and then then we'll use TR CCH first we'll call await Firebase fire. instance. collection here we are creating collection user data we are creating a document of the user ID current user ID and then we are setting the data that we have created and now after that we are printing the document is added in cat we just print the error if any error occurs we can also print error in Saving to P St and the error now we need to call the save user token when we are retrieving the FM token inside our notification service. here we when we are calling the init function at that time we are just getting the token but we are calling this init function in our main. [Music] file after we are launching the app we are calling the init function but since we have written the logic that we cannot write in our database if we are not authenticated for that we need to separate the logic for getting the token here will write another function it will be static future get device token and here we'll make it async and after that we'll be getting the token now if we call this function get device token we'll be get getting the token and by this point we also need to save the device token to Fire 2 now here first we'll be checking if the user is logged in or not so we'll use that at OD service. is logged in function it will return either true or false and then if the user is logged in then in that case we'll be saving the token to fir store and we'll be printing save to fire store and also if the token changes we also need to listen to it for that we'll be using Firebase messaging. on toen refresh. lesson this event will get called when the fcm changes at that time it will be also same we'll check if the user is logged in then we will save the token now we need to call this get device token function inside our homepage so visit home. that file we'll call it inside init State push notifications do get device token now the user that we are declaring here will not get changed if we call the sa user token function so if somebody logs in log out in that case it might cause a problem for that let's not make it a static variable and use this user here and every time we call the user we'll call Firebase do instance. current user and after that we'll be saving it to collection of user data of document user do user uid and then we can say document added to dollar user. uid now we are calling the push notifications. getet notification inside our push notifications. get devise token in homepage now if we try to log in now currently our P2 database is mty if you just login you'll find it is giving that document added to this document ID now if you check it's not showing anything just refresh now it's giving the user ID the email and the fcm token now if we log out and register with another account now here our account got created and it's shown document save to this user ID now as you can see the email is different but the device token is same now this is how we can save the FM token inside our fire store database so that's all for this video I hope that now we'll be able to integrate push notifications inside your flutter application so thank you
Info
Channel: Snehasis Ghosh
Views: 10,023
Rating: undefined out of 5
Keywords: Snehasis Ghosh, flutter, firebase, firebase cloud messaging, flutter push notification, local notifications, push notifications flutter, Flutter Firebase Integration, Flutter Notification System, Firebase Cloud Messaging in Flutter, Local Notifications in Flutter, Push Notification Handling Flutter, Flutter Notification Payload Handling, Real-time Notifications in Flutter, Flutter Notification Best Practices, flutter tutorial, how to send notification in app using firebase
Id: JwFiALyfD-0
Channel Id: undefined
Length: 53min 20sec (3200 seconds)
Published: Fri Apr 05 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.