SlideShare a Scribd company logo
1 of 22
Download to read offline
Cloud Messaging
Firebase Cloud Messaging with Flutter
Muhammad Ali 70132700
Create a Flutter Project
• First, we are going to create a flutter project. For that, we must have the Flutter
SDK installed in our system. You can find simple steps for flutter installation in the
official documentation.
• After you've successfully installed Flutter, you can simply run the following
command in your desired directory to set up a complete Flutter project:
• You can simply run the following command in your desired directory to set up a
complete Flutter project
Flutter create pushNotification
• Execute the following command in the terminal to run the project
Flutter run
Integrate Firebase Configuration with Flutter
In this step, we are going to integrate Firebase services with our Flutter project. But first, we need to
create a Firebase project. The setup guidelines are also provided in the official firebase
documentation for Flutter.
1. Then a window will appear asking to input the project's name. Here, I've kept the project
name as Flutter pushNotification
2. We can continue to the next step when the project has been created. After the project
has been set up, we will get a project console.
Register Firebase to Your Android App
• As the registration process is platform-specific, we are going to register our app for the Android
platform. After clicking on the Android icon, we will be directed to an interface asking for
the Android package name.
• The package name will be available in the ./android/app/build.gradle file of your Flutter project. You
will see something like this:
com.example.pushNotification
• We just need to copy it and paste it to the Android package name input field as shown in the
screenshot below:
Add Firebase Configurations to Native Files in
your Flutter Project
• First in our root-level (project-level) Gradle file (android/build.gradle), we need to add rules to
include the Google Services Gradle plugin. We need to check if the following configurations are
available or not:
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// Add this line
classpath 'com.google.gms:google-services:4.3.4'
}
}
allprojects {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
}
Add Firebase Configurations to Native Files in
your Flutter Project
• Now in our module (app-level) Gradle file (android/app/build.gradle), we need to apply the Google Services
Gradle plugin.
• For that, we need to add the piece of code highlighted in the following code snippet to
the ./android/app/build.gradle file of our project:
• Now, we need to run the following command so that some automatic configurations can be made:
// Add the following line:
**apply plugin: 'com.google.gms.google-services'** //
Google Services plugin
android {
// ...
}
flutter packages get
• With that we have successfully integrated Firebase
configurations with our Flutter project.
Integrate Firebase Messaging with Flutter
• First, we need to add the firebase-messaging dependency to the ./android/app/build.gardle file. In the file,
we need to add the following dependencies:
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-
jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-
messaging:20.1.0'
}
• Next, we need to add an action and a category as an intent-filter within the activity tag in the
./android/app/src/main/AndroidManifest.xml file:
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT"
/>
</intent-filter>
• Now, we need to create a Java file called Application.java in the
path /android/app/src/main/java/<app-organization-path>.
Integrate Firebase Messaging with Flutter
• Then, we need to add the code from the following code snippet inside
it:
package io.flutter.plugins.pushNotification;
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
@Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
@Override
public void registerWith(PluginRegistry registry) {
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}
Install the Firebase Messaging Package
• Here, we are going to use the [firebase_messaging] package, which you can find here. For that, we need to
add the plugin to the dependency option of the pubspec.yaml file.
• We need to add the following line of code to the dependencies option:
firebase_messaging: ^7.0.3
Implement a Simple UI Screen
• Now, inside the MyHomePage stateful widget class of the main.dart file, we need to initialize the
FirebaseMessaging instance and some constants as shown in the code snippet below:
String messageTitle = "Empty";
String notificationAlert = "alert";
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
• The messageTitle variable will receive the notification message title and notificationAlert will
be assigned the action that's been completed once the notification comes up.
• Now, we need to apply these variables to the build function inside the Scaffold widget body
as shown in the code snippet below:
Implement a Simple UI Screen
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
notificationAlert,),
Text(
messageTitle,
style: Theme.of(context).textTheme.headline4,
),],),),);}
Implement a Simple UI Screen
• For now, the notification title is empty, and the alert is also as
defined. We need to assign a proper value to them once we receive
the notification message.
• So we need to configure the code to receive the notification and use
the notification message to display it on the screen.
• For that, we need to add the code from the following code snippet in
the initiState function:
Implement a Simple UI Screen
@override
void initState() {
// TODO: implement initState
super.initState();
_firebaseMessaging.configure(
onMessage: (message) async{
setState(() {
messageTitle = message["notification"]["title"];
notificationAlert = "New Notification Alert";
});},
onResume: (message) async{
setState(() {
messageTitle = message["data"]["title"];
notificationAlert = "Application opened from Notification";
});},);}
Implement a Simple UI Screen
• Here, we have used the configure method provided by
_firebaseMessaging instance which in turn provides the onMessage
and onResume callbacks. These callbacks provide the notification
message as a parameter. The message response will hold the
notification object as a map object.
• The onMessage function triggers when the notification is received
while we are running the app. The onResume function triggers when
we receive the notification alert in the device notification bar and
opens the app through the push notification itself. In this case, the
app can be running in the background or not running at all.
Create a Message from the Firebase Cloud
Messaging Console
FCM relies on the following set of components that build, transport, and receive messages:
1.Tooling to compose or build message requests. The Notifications composer provides a GUI-based option for creating notification requests. For full
automation and support for all message types, you must build message requests in a trusted server environment that supports the Firebase Admin
SDK or the FCM server protocols. This environment could be Cloud Functions for Firebase, App Engine, or your own app server.
Create a Message from the Firebase Cloud
Messaging Console
• First, we need to go back to the Cloud Messaging console in the
Firebase site as shown in the image below:
Create a Message from the Firebase Cloud
Messaging Console
• Here, we can see the 'Send your first message' option in the window,
as we have not configured any messages before. We need to click on
it which will lead us to the following window:
Create a Message from the Firebase Cloud
Messaging Console
• Here, we can enter the title, text, image, and name of the notification. The title
we set here will be provided as the title in the message object on the callbacks
we set before in the Flutter project.
• After setting the required fields, we can click on 'Next' which will lead us to the
following window:
Create a Message from the Firebase Cloud
Messaging Console
• Here, we need to provide our target app and click on 'Next'.
• For Scheduling we can keep the default option:
• Next, the Conversion window will appear which we can keep as
default as well, and then click on the 'Next' button.
Create a Message from the Firebase Cloud
Messaging Console
• Lastly, a window where we need to enter the custom data will appear
in which we can set the title and click_action. This click action event is
triggered whenever we click on the notification that appears in the
notification bar of the device.
Create a Message from the Firebase Cloud
Messaging Console
• Now, we are ready to send the first notification message to the
device. First, let's try it with the device running in the emulator.
• As we click on the 'Review' button and send the message, we will get
the following result in the Cloud Messaging console as well as the
emulator:
Conclusion
• Push notifications are essential in any app. They can be used to alert
users to what's going on in the app, and can help drive users' interest
back to the app.
• Additionally, Firebase Cloud Messaging makes sending notification
alerts much simpler and easier.
• In this tutorial, we started by configuring the Firebase app and then
moved on to the setup and implementation of the Firebase
messaging configuration in the Flutter app. Lastly, we were able to
send notification alerts to the app using Firebase Cloud Messaging.

More Related Content

Similar to Cloud Messaging Flutter

Building Extensible RIAs with MEF
Building Extensible RIAs with MEFBuilding Extensible RIAs with MEF
Building Extensible RIAs with MEFGlenn Block
 
MAD mobile application development you can learn from here , we perform all c...
MAD mobile application development you can learn from here , we perform all c...MAD mobile application development you can learn from here , we perform all c...
MAD mobile application development you can learn from here , we perform all c...harshalpatil183931
 
React Native Firebase Realtime Database + Authentication
React Native Firebase Realtime Database + AuthenticationReact Native Firebase Realtime Database + Authentication
React Native Firebase Realtime Database + AuthenticationKobkrit Viriyayudhakorn
 
Titanium Appcelerator - Beginners
Titanium Appcelerator - BeginnersTitanium Appcelerator - Beginners
Titanium Appcelerator - BeginnersAmbarish Hazarnis
 
M365 global developer bootcamp 2019 PA
M365 global developer bootcamp 2019  PAM365 global developer bootcamp 2019  PA
M365 global developer bootcamp 2019 PAThomas Daly
 
I/O Extended (GDG Bogor) - Sidiq Permana
I/O Extended (GDG Bogor) - Sidiq PermanaI/O Extended (GDG Bogor) - Sidiq Permana
I/O Extended (GDG Bogor) - Sidiq PermanaDicoding
 
GoogleDSC_ GHRCE_ flutter_firebase.pptx
GoogleDSC_ GHRCE_  flutter_firebase.pptxGoogleDSC_ GHRCE_  flutter_firebase.pptx
GoogleDSC_ GHRCE_ flutter_firebase.pptxGoogleDeveloperStude22
 
Flutter movie apps tutor
Flutter movie apps tutorFlutter movie apps tutor
Flutter movie apps tutorHerry Prasetyo
 
Keynote + Next Gen UIs.pptx
Keynote + Next Gen UIs.pptxKeynote + Next Gen UIs.pptx
Keynote + Next Gen UIs.pptxEqraKhattak
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Katy Slemon
 
Local Notification Tutorial
Local Notification TutorialLocal Notification Tutorial
Local Notification TutorialKetan Raval
 
Androidreadme
AndroidreadmeAndroidreadme
Androidreadmeiderdik
 
Deployingmuleapplications 160903085602
Deployingmuleapplications 160903085602Deployingmuleapplications 160903085602
Deployingmuleapplications 160903085602ppts123456
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestJoshua Warren
 
Extending the Enterprise with MEF
Extending the Enterprise with MEFExtending the Enterprise with MEF
Extending the Enterprise with MEFBrian Ritchie
 
Deploying mule applications
Deploying mule applicationsDeploying mule applications
Deploying mule applicationsBhargav Ranjit
 

Similar to Cloud Messaging Flutter (20)

Cloud hub deployment
Cloud hub deploymentCloud hub deployment
Cloud hub deployment
 
Building Extensible RIAs with MEF
Building Extensible RIAs with MEFBuilding Extensible RIAs with MEF
Building Extensible RIAs with MEF
 
MAD mobile application development you can learn from here , we perform all c...
MAD mobile application development you can learn from here , we perform all c...MAD mobile application development you can learn from here , we perform all c...
MAD mobile application development you can learn from here , we perform all c...
 
Dense And Hot Web Du
Dense And Hot  Web DuDense And Hot  Web Du
Dense And Hot Web Du
 
React Native Firebase Realtime Database + Authentication
React Native Firebase Realtime Database + AuthenticationReact Native Firebase Realtime Database + Authentication
React Native Firebase Realtime Database + Authentication
 
Web Os Hands On
Web Os Hands OnWeb Os Hands On
Web Os Hands On
 
Titanium Appcelerator - Beginners
Titanium Appcelerator - BeginnersTitanium Appcelerator - Beginners
Titanium Appcelerator - Beginners
 
M365 global developer bootcamp 2019 PA
M365 global developer bootcamp 2019  PAM365 global developer bootcamp 2019  PA
M365 global developer bootcamp 2019 PA
 
I/O Extended (GDG Bogor) - Sidiq Permana
I/O Extended (GDG Bogor) - Sidiq PermanaI/O Extended (GDG Bogor) - Sidiq Permana
I/O Extended (GDG Bogor) - Sidiq Permana
 
Sencha Touch MVC
Sencha Touch MVCSencha Touch MVC
Sencha Touch MVC
 
GoogleDSC_ GHRCE_ flutter_firebase.pptx
GoogleDSC_ GHRCE_  flutter_firebase.pptxGoogleDSC_ GHRCE_  flutter_firebase.pptx
GoogleDSC_ GHRCE_ flutter_firebase.pptx
 
Flutter movie apps tutor
Flutter movie apps tutorFlutter movie apps tutor
Flutter movie apps tutor
 
Keynote + Next Gen UIs.pptx
Keynote + Next Gen UIs.pptxKeynote + Next Gen UIs.pptx
Keynote + Next Gen UIs.pptx
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...
 
Local Notification Tutorial
Local Notification TutorialLocal Notification Tutorial
Local Notification Tutorial
 
Androidreadme
AndroidreadmeAndroidreadme
Androidreadme
 
Deployingmuleapplications 160903085602
Deployingmuleapplications 160903085602Deployingmuleapplications 160903085602
Deployingmuleapplications 160903085602
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
 
Extending the Enterprise with MEF
Extending the Enterprise with MEFExtending the Enterprise with MEF
Extending the Enterprise with MEF
 
Deploying mule applications
Deploying mule applicationsDeploying mule applications
Deploying mule applications
 

Recently uploaded

Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 

Recently uploaded (20)

Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 

Cloud Messaging Flutter

  • 1. Cloud Messaging Firebase Cloud Messaging with Flutter Muhammad Ali 70132700
  • 2. Create a Flutter Project • First, we are going to create a flutter project. For that, we must have the Flutter SDK installed in our system. You can find simple steps for flutter installation in the official documentation. • After you've successfully installed Flutter, you can simply run the following command in your desired directory to set up a complete Flutter project: • You can simply run the following command in your desired directory to set up a complete Flutter project Flutter create pushNotification • Execute the following command in the terminal to run the project Flutter run
  • 3. Integrate Firebase Configuration with Flutter In this step, we are going to integrate Firebase services with our Flutter project. But first, we need to create a Firebase project. The setup guidelines are also provided in the official firebase documentation for Flutter. 1. Then a window will appear asking to input the project's name. Here, I've kept the project name as Flutter pushNotification 2. We can continue to the next step when the project has been created. After the project has been set up, we will get a project console.
  • 4. Register Firebase to Your Android App • As the registration process is platform-specific, we are going to register our app for the Android platform. After clicking on the Android icon, we will be directed to an interface asking for the Android package name. • The package name will be available in the ./android/app/build.gradle file of your Flutter project. You will see something like this: com.example.pushNotification • We just need to copy it and paste it to the Android package name input field as shown in the screenshot below:
  • 5. Add Firebase Configurations to Native Files in your Flutter Project • First in our root-level (project-level) Gradle file (android/build.gradle), we need to add rules to include the Google Services Gradle plugin. We need to check if the following configurations are available or not: buildscript { repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository } dependencies { // Add this line classpath 'com.google.gms:google-services:4.3.4' } } allprojects { repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository } }
  • 6. Add Firebase Configurations to Native Files in your Flutter Project • Now in our module (app-level) Gradle file (android/app/build.gradle), we need to apply the Google Services Gradle plugin. • For that, we need to add the piece of code highlighted in the following code snippet to the ./android/app/build.gradle file of our project: • Now, we need to run the following command so that some automatic configurations can be made: // Add the following line: **apply plugin: 'com.google.gms.google-services'** // Google Services plugin android { // ... } flutter packages get • With that we have successfully integrated Firebase configurations with our Flutter project.
  • 7. Integrate Firebase Messaging with Flutter • First, we need to add the firebase-messaging dependency to the ./android/app/build.gardle file. In the file, we need to add the following dependencies: dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib- jdk7:$kotlin_version" implementation 'com.google.firebase:firebase- messaging:20.1.0' } • Next, we need to add an action and a category as an intent-filter within the activity tag in the ./android/app/src/main/AndroidManifest.xml file: <intent-filter> <action android:name="FLUTTER_NOTIFICATION_CLICK" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> • Now, we need to create a Java file called Application.java in the path /android/app/src/main/java/<app-organization-path>.
  • 8. Integrate Firebase Messaging with Flutter • Then, we need to add the code from the following code snippet inside it: package io.flutter.plugins.pushNotification; import io.flutter.app.FlutterApplication; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback; import io.flutter.plugins.GeneratedPluginRegistrant; import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin; import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService; public class Application extends FlutterApplication implements PluginRegistrantCallback { @Override public void onCreate() { super.onCreate(); FlutterFirebaseMessagingService.setPluginRegistrant(this); } @Override public void registerWith(PluginRegistry registry) { FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")); } }
  • 9. Install the Firebase Messaging Package • Here, we are going to use the [firebase_messaging] package, which you can find here. For that, we need to add the plugin to the dependency option of the pubspec.yaml file. • We need to add the following line of code to the dependencies option: firebase_messaging: ^7.0.3
  • 10. Implement a Simple UI Screen • Now, inside the MyHomePage stateful widget class of the main.dart file, we need to initialize the FirebaseMessaging instance and some constants as shown in the code snippet below: String messageTitle = "Empty"; String notificationAlert = "alert"; FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); • The messageTitle variable will receive the notification message title and notificationAlert will be assigned the action that's been completed once the notification comes up. • Now, we need to apply these variables to the build function inside the Scaffold widget body as shown in the code snippet below:
  • 11. Implement a Simple UI Screen Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( notificationAlert,), Text( messageTitle, style: Theme.of(context).textTheme.headline4, ),],),),);}
  • 12. Implement a Simple UI Screen • For now, the notification title is empty, and the alert is also as defined. We need to assign a proper value to them once we receive the notification message. • So we need to configure the code to receive the notification and use the notification message to display it on the screen. • For that, we need to add the code from the following code snippet in the initiState function:
  • 13. Implement a Simple UI Screen @override void initState() { // TODO: implement initState super.initState(); _firebaseMessaging.configure( onMessage: (message) async{ setState(() { messageTitle = message["notification"]["title"]; notificationAlert = "New Notification Alert"; });}, onResume: (message) async{ setState(() { messageTitle = message["data"]["title"]; notificationAlert = "Application opened from Notification"; });},);}
  • 14. Implement a Simple UI Screen • Here, we have used the configure method provided by _firebaseMessaging instance which in turn provides the onMessage and onResume callbacks. These callbacks provide the notification message as a parameter. The message response will hold the notification object as a map object. • The onMessage function triggers when the notification is received while we are running the app. The onResume function triggers when we receive the notification alert in the device notification bar and opens the app through the push notification itself. In this case, the app can be running in the background or not running at all.
  • 15. Create a Message from the Firebase Cloud Messaging Console FCM relies on the following set of components that build, transport, and receive messages: 1.Tooling to compose or build message requests. The Notifications composer provides a GUI-based option for creating notification requests. For full automation and support for all message types, you must build message requests in a trusted server environment that supports the Firebase Admin SDK or the FCM server protocols. This environment could be Cloud Functions for Firebase, App Engine, or your own app server.
  • 16. Create a Message from the Firebase Cloud Messaging Console • First, we need to go back to the Cloud Messaging console in the Firebase site as shown in the image below:
  • 17. Create a Message from the Firebase Cloud Messaging Console • Here, we can see the 'Send your first message' option in the window, as we have not configured any messages before. We need to click on it which will lead us to the following window:
  • 18. Create a Message from the Firebase Cloud Messaging Console • Here, we can enter the title, text, image, and name of the notification. The title we set here will be provided as the title in the message object on the callbacks we set before in the Flutter project. • After setting the required fields, we can click on 'Next' which will lead us to the following window:
  • 19. Create a Message from the Firebase Cloud Messaging Console • Here, we need to provide our target app and click on 'Next'. • For Scheduling we can keep the default option: • Next, the Conversion window will appear which we can keep as default as well, and then click on the 'Next' button.
  • 20. Create a Message from the Firebase Cloud Messaging Console • Lastly, a window where we need to enter the custom data will appear in which we can set the title and click_action. This click action event is triggered whenever we click on the notification that appears in the notification bar of the device.
  • 21. Create a Message from the Firebase Cloud Messaging Console • Now, we are ready to send the first notification message to the device. First, let's try it with the device running in the emulator. • As we click on the 'Review' button and send the message, we will get the following result in the Cloud Messaging console as well as the emulator:
  • 22. Conclusion • Push notifications are essential in any app. They can be used to alert users to what's going on in the app, and can help drive users' interest back to the app. • Additionally, Firebase Cloud Messaging makes sending notification alerts much simpler and easier. • In this tutorial, we started by configuring the Firebase app and then moved on to the setup and implementation of the Firebase messaging configuration in the Flutter app. Lastly, we were able to send notification alerts to the app using Firebase Cloud Messaging.