SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Push Notifications: How to add
them to a Flutter App
https://fibonalabs.com/
Introduction
One of the most efficient ways to engage customers with your app is the
introduction of push notifications. Whether a person is using the app or not,
push notifications will notify them about all the latest updates that your app
offers. And if an app is created using Flutter this task becomes even easier.
Using Google’s Firebase Cloud Messaging platform, you can add push
notifications to your app.
The benefits of adding push notifications using Flutter are:
1. Increases user retention i.e. a greater number of users download the app
2. Increases user engagement in the app
3. Significant increase in the conversion rate
4. Keeps track of user metrics
5. Improved user experience
How to Introduce Push Notifications In Your App?
With the fame that Flutter has garnered over the years, it has become the top
choice of business owners for cross-platform mobile app development. With the
enhancement of features like push notifications, it has further made its place
STEP 1: Set up and create a new Firebase project
● Log in to your Google account and access the Firebase console.
● Click “Add Project”, enter the project name, and click “Continue”.
● Next, disable Google Analytics and click “Create Project”. The Firebase
Project will be created.
● Once the project is initialized, click “Continue” to land on the Project
Overview Screen.
STEP 2: Integrate the Firebase Project with your Android App
● Firstly, create a Flutter application using the command “flutter create notify”
and open it in your IDE.
● Now, click on the Android icon, shown on the Project Overview Screen and
it will direct you to a form.
● Fill in the following details:
Android package name (get it from the following path project directory →
android → app → src → main → AndroidManifest.xml).
Next, enter a nickname for your app (optional).
Enter SHA-1 hash (click on the help icon to know where to get the SHA-1
hash value)
● Click “Register app” and your app will be registered.
● Next, download the google-services.json file, drag and drop it to the
following path project directory → android → app, and click “Next”.
● Add Firebase SDK using the code snippet below and click “Next”.
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 {
google() // Google's Maven repository
...
}
}
● Now, apply google-plugin-services to the Gradle files.
● Lastly, click “Continue to console” and your Firebase set-up for the Android
app will be completed.
STEP 3: Install Firebase Plugins
With the help of firebase cloud messaging, the most important step for adding
Push Notifications is explained below, follow carefully. There are three plugins
required for this sample project, which are:
● firebase_core: Helps in using Firebases service with the Flutter app.
● firebase_messaging: Helps in receiving notifications in the Flutter app.
● overlay_support: Helps in building overlay UI.
To add these packages to your project:
● Get their latest version from the pub.dev.
● Add these packages to the pubspec.yaml file of your Flutter Project using
the command below:
flutter pub add firebase_core //installs firebase core
flutter pub add firebase_messaging //installs firebase massaging package
flutter pub add overlay_support //installs overlay support
● Look for dependencies in the pusbspec.yaml file. The added dependencies
should be:
dependencies:
firebase_core: ^1.13.1
firebase_messaging: ^11.2.11
overlay_support: ^1.2.1
STEP 4: Create a UI for Flutter App and Add Push Notification
Functionality
It is per your convenience and interest that you can build a Flutter UI. Here, I
have purposely skipped the details for UI creation as I want to focus on the
Push Notification functionality of the app.
● The first step here is to define a variable for FirebaseMessaging. For that,
run the following command:
class _HomePageState extends State {
late final FirebaseMessaging _messaging;
// ...
@override
Widget build(BuildContext context) {
// ...
}
● Then, create a method as registerNotification() inside the class
_HomePageState. This helps in initializing the Firebase app and
instantiating Firebase Messaging.
void registerNotification() async {
// 1. Initialize the Firebase app
await Firebase.initializeApp();
// 2. Instantiate Firebase Messaging
_messaging = FirebaseMessaging.instance;
● Now, to receive a Push Notification on your device and make changes in
the UI, run the command below:
void registerNotification() async {
//...
if (settings.authorizationStatus ==
AuthorizationStatus.authorized) {
print('User granted permission');
// For handling the received notifications
{
// Parse the message received
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
);
setState(() {
_notificationInfo = notification;
_totalNotifications++;
});
} else {
print('User declined or has not accepted permission');
}
}
By now you must be aware of the fact that PushNotification is a model class
that stores notification content. It should look like this:
Step 5: Sending Push Notification in your Flutter app
If you got to step 3, you will find we have used an overlays-support plugin. This
comes into action now. Here we will show how firebase cloud messaging has
made it easy for you to receive the notifications while:
1. the app is in use
2. the app is in minimized state
3. App is in a closed state
When App is in use
● Now, you can create a sample or a custom UI effect for Push Notification
when it arrives on your device.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return OverlaySupport(
child: MaterialApp(
// ...
),
}
}
● Now to display the Push Notification inside your app use the function
showSimpleNotification().
void registerNotification() async {
//…
if (settings.authorizationStatus ==
AuthorizationStatus.authorized) {
{
// ...
if (_notificationInfo != null) {
// For displaying the notification as an overlay
showSimpleNotification(
Text(_notificationInfo!.title!),
leading: NotificationBadge(totalNotifications:
_totalNotifications),
subtitle: Text(_notificationInfo!.body!),
duration: Duration(seconds: 2),
);
}
});
} else {
print('User declined or has not accepted permission');
}
}
● Next, you have to use two variables to display the notification information,
namely, _notificationInfo and _totalNotifications.
class _HomePageState extends State {
late int _totalNotifications;
PushNotification? _notificationInfo;
//…
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Notify'),
brightness: Brightness.dark,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
//...
_notificationInfo != null
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'TITLE: ${_notificationInfo!.title}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
),
SizedBox(height: 8.0),
Text(
'BODY: ${_notificationInfo!.body}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
),
),
)
: Container(),
],
),
);
}
}
Shown above is a column with the two text widgets i.e., notification title and
body.
When App is in Minimized State
● To handle Push Notifications while the app is in terminated state, we need
to define a top-level function. This function
_firebaseMessagingBackgroundHandler(), should not be included in any of
the classes defined
Firstly, define the above function as shown below:
Future _firebaseMessagingBackgroundHandler(RemoteMessage message)
async {
print("Handling a background message: ${message.messageId}");
}
Now, call the method onBackgroundMessage().
void registerNotification() async {
await Firebase.initializeApp();
_messaging = FirebaseMessaging.instance;
// Add the following line
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackground
Handler);
// ...
}
● If your app is running in the background and you tapped on the received
notification, then this action needs to be handled using the initState()
@override
void initState() {
//...
// For handling notification when the app is in background
// but not terminated
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message)
{
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
);
setState(() {
_totalNotifications++;
});
});
super.initState();
}
When App is in Closed State
As we know, Push Notifications can also be sent while the app is in the
terminated state. So, let’s see what commands we need to run while we open
the notification in the app’s closed state.
For this, the first step is to define checkForInitialMessage() in this method.
// For handling notification when the app is in terminated state
checkForInitialMessage() async {
await Firebase.initializeApp();
RemoteMessage? initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
PushNotification notification = PushNotification(
title: initialMessage.notification?.title,
body: initialMessage.notification?.body,
);
setState(() {
_notificationInfo = notification;
_totalNotifications++;
});
}
Next, call this method, for iniState method().
@override
void initState() {
// ...
// Call here
checkForInitialMessage();
// ...
}
STEP 6: Sample Testing of Flutter Push Notifications on Android Device
In order to run this app on an Android device, follow the steps below.
● Go to android → app → build.gradle and enable multidex support, using
the command:
android {
defaultConfig {
// ...
multiDexEnabled true
● Add <intent-filter> tag inside <activity> (follow this path android → app →
src → main → AndroidManifest.xml). This tag will help you in retrieving the
message at the time of notification’s arrival.
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="<your_package_name>">
<application
android:label="notify"
android:icon="@mipmap/ic_launcher">
android:name=".MainActivity"
<!-- ... -->
<!-- Add this tag -->
<intent-filter>
<action
android:name="FLUTTER_NOTIFICATION_CLICK" />
<category
android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- ... -->
</application>
</manifest>
You can also add additional messages using Firebase console.
This way you can add Push Notifications using firebase cloud messaging in
Flutter apps.
THANK YOU

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to docker
Introduction to dockerIntroduction to docker
Introduction to docker
John Willis
 
Android installation
Android installationAndroid installation
Android installation
Durai S
 

Was ist angesagt? (20)

Docker by Example - Basics
Docker by Example - Basics Docker by Example - Basics
Docker by Example - Basics
 
Node.js
Node.jsNode.js
Node.js
 
Kotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a treeKotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a tree
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Docker 101: An Introduction
Docker 101: An IntroductionDocker 101: An Introduction
Docker 101: An Introduction
 
Web Worker, Service Worker and Worklets
Web Worker, Service Worker and WorkletsWeb Worker, Service Worker and Worklets
Web Worker, Service Worker and Worklets
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
 
How to install android sdk
How to install android sdkHow to install android sdk
How to install android sdk
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Deep dive into React Portals
Deep dive into React PortalsDeep dive into React Portals
Deep dive into React Portals
 
Android's HIDL: Treble in the HAL
Android's HIDL: Treble in the HALAndroid's HIDL: Treble in the HAL
Android's HIDL: Treble in the HAL
 
Angular
AngularAngular
Angular
 
Kubernetes Probes (Liveness, Readyness, Startup) Introduction
Kubernetes Probes (Liveness, Readyness, Startup) IntroductionKubernetes Probes (Liveness, Readyness, Startup) Introduction
Kubernetes Probes (Liveness, Readyness, Startup) Introduction
 
Google Firebase
Google FirebaseGoogle Firebase
Google Firebase
 
Introduction to docker
Introduction to dockerIntroduction to docker
Introduction to docker
 
Intro To Android App Development
Intro To Android App DevelopmentIntro To Android App Development
Intro To Android App Development
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Docker Containers - Talk Linux Day 2015
Docker Containers - Talk Linux Day 2015Docker Containers - Talk Linux Day 2015
Docker Containers - Talk Linux Day 2015
 
Android installation
Android installationAndroid installation
Android installation
 
CI CD Jenkins for Swift Deployment
CI CD Jenkins for Swift DeploymentCI CD Jenkins for Swift Deployment
CI CD Jenkins for Swift Deployment
 

Ähnlich wie Push Notifications: How to add them to a Flutter App

How to create android push notifications with custom view
How to create android push notifications with custom viewHow to create android push notifications with custom view
How to create android push notifications with custom view
PushApps - Content Recommendation in Push Notifications
 

Ähnlich wie Push Notifications: How to add them to a Flutter App (20)

Cloud Messaging Flutter
Cloud Messaging FlutterCloud Messaging Flutter
Cloud Messaging Flutter
 
Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...
 
How to create android push notifications with custom view
How to create android push notifications with custom viewHow to create android push notifications with custom view
How to create android push notifications with custom view
 
Firebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsFirebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript Apps
 
Email authentication using firebase auth + flutter
Email authentication using firebase auth + flutterEmail authentication using firebase auth + flutter
Email authentication using firebase auth + flutter
 
Build Location Based App on bada
Build Location Based App on badaBuild Location Based App on bada
Build Location Based App on bada
 
Android 103 - Firebase and Architecture Components
Android 103 - Firebase and Architecture ComponentsAndroid 103 - Firebase and Architecture Components
Android 103 - Firebase and Architecture Components
 
How to Use Firebase to Send Push Notifications to React Native and Node.js Apps
How to Use Firebase to Send Push Notifications to React Native and Node.js AppsHow to Use Firebase to Send Push Notifications to React Native and Node.js Apps
How to Use Firebase to Send Push Notifications to React Native and Node.js Apps
 
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
Firebase crashlytics integration in iOS swift (dSYM File Required Problem Res...
 
Overview of wrap Features in Power Apps.pptx
Overview of wrap Features in Power Apps.pptxOverview of wrap Features in Power Apps.pptx
Overview of wrap Features in Power Apps.pptx
 
How Firebase Works With React Native Push Notifications
How Firebase Works With React Native Push NotificationsHow Firebase Works With React Native Push Notifications
How Firebase Works With React Native Push Notifications
 
What is new in Firebase?
What is new in Firebase?What is new in Firebase?
What is new in Firebase?
 
Push Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKPush Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDK
 
Push Notification with Unity in iOS using App42 Backend
Push Notification with Unity in iOS using App42 BackendPush Notification with Unity in iOS using App42 Backend
Push Notification with Unity in iOS using App42 Backend
 
Firebase
FirebaseFirebase
Firebase
 
Dense And Hot Web Du
Dense And Hot  Web DuDense And Hot  Web Du
Dense And Hot Web Du
 
Sencha Touch MVC
Sencha Touch MVCSencha Touch MVC
Sencha Touch MVC
 
Local Notification Tutorial
Local Notification TutorialLocal Notification Tutorial
Local Notification Tutorial
 
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
Complete steps to Integrate Push Notification for Your Cocos2dx App with Push...
 
Importance Of Alert And Notification In App Dev
Importance Of Alert And Notification In App DevImportance Of Alert And Notification In App Dev
Importance Of Alert And Notification In App Dev
 

Mehr von Fibonalabs

Mehr von Fibonalabs (20)

Data Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJSData Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJS
 
A Complete Guide to Building a Ground-Breaking UX Design Strategy
A Complete Guide to Building a Ground-Breaking UX Design StrategyA Complete Guide to Building a Ground-Breaking UX Design Strategy
A Complete Guide to Building a Ground-Breaking UX Design Strategy
 
React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?
 
Measures to ensure Cyber Security in a serverless environment
Measures to ensure Cyber Security in a serverless environmentMeasures to ensure Cyber Security in a serverless environment
Measures to ensure Cyber Security in a serverless environment
 
Simplifying CRUD operations using budibase
Simplifying CRUD operations using budibaseSimplifying CRUD operations using budibase
Simplifying CRUD operations using budibase
 
How to implement Micro-frontends using Qiankun
How to implement Micro-frontends using QiankunHow to implement Micro-frontends using Qiankun
How to implement Micro-frontends using Qiankun
 
Different Cloud Computing Services Used At Fibonalabs
Different Cloud Computing Services Used At FibonalabsDifferent Cloud Computing Services Used At Fibonalabs
Different Cloud Computing Services Used At Fibonalabs
 
How Can A Startup Benefit From Collaborating With A UX Design Partner
How Can A Startup Benefit From Collaborating With A UX Design PartnerHow Can A Startup Benefit From Collaborating With A UX Design Partner
How Can A Startup Benefit From Collaborating With A UX Design Partner
 
How to make React Applications SEO-friendly
How to make React Applications SEO-friendlyHow to make React Applications SEO-friendly
How to make React Applications SEO-friendly
 
10 Heuristic Principles
10 Heuristic Principles10 Heuristic Principles
10 Heuristic Principles
 
Key Skills Required for Data Engineering
Key Skills Required for Data EngineeringKey Skills Required for Data Engineering
Key Skills Required for Data Engineering
 
Ways for UX Design Iterations: Innovate Faster & Better
Ways for UX Design Iterations: Innovate Faster & BetterWays for UX Design Iterations: Innovate Faster & Better
Ways for UX Design Iterations: Innovate Faster & Better
 
Factors that could impact conversion rate in UX Design
Factors that could impact conversion rate in UX DesignFactors that could impact conversion rate in UX Design
Factors that could impact conversion rate in UX Design
 
Information Architecture in UX: To offer Delightful and Meaningful User Exper...
Information Architecture in UX: To offer Delightful and Meaningful User Exper...Information Architecture in UX: To offer Delightful and Meaningful User Exper...
Information Architecture in UX: To offer Delightful and Meaningful User Exper...
 
Cloud Computing Architecture: Components, Importance, and Tips
Cloud Computing Architecture: Components, Importance, and TipsCloud Computing Architecture: Components, Importance, and Tips
Cloud Computing Architecture: Components, Importance, and Tips
 
Choose the Best Agile Product Development Method for a Successful Business
Choose the Best Agile Product Development Method for a Successful BusinessChoose the Best Agile Product Development Method for a Successful Business
Choose the Best Agile Product Development Method for a Successful Business
 
Atomic Design: Effective Way of Designing UI
Atomic Design: Effective Way of Designing UIAtomic Design: Effective Way of Designing UI
Atomic Design: Effective Way of Designing UI
 
Agile Software Development with Scrum_ A Complete Guide to The Steps in Agile...
Agile Software Development with Scrum_ A Complete Guide to The Steps in Agile...Agile Software Development with Scrum_ A Complete Guide to The Steps in Agile...
Agile Software Development with Scrum_ A Complete Guide to The Steps in Agile...
 
7 Psychology Theories in UX to Provide Better User Experience
7 Psychology Theories in UX to Provide Better User Experience7 Psychology Theories in UX to Provide Better User Experience
7 Psychology Theories in UX to Provide Better User Experience
 
Moving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should KnowMoving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should Know
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 

Push Notifications: How to add them to a Flutter App

  • 1. Push Notifications: How to add them to a Flutter App https://fibonalabs.com/
  • 2.
  • 3. Introduction One of the most efficient ways to engage customers with your app is the introduction of push notifications. Whether a person is using the app or not, push notifications will notify them about all the latest updates that your app offers. And if an app is created using Flutter this task becomes even easier. Using Google’s Firebase Cloud Messaging platform, you can add push notifications to your app. The benefits of adding push notifications using Flutter are:
  • 4. 1. Increases user retention i.e. a greater number of users download the app 2. Increases user engagement in the app 3. Significant increase in the conversion rate 4. Keeps track of user metrics 5. Improved user experience How to Introduce Push Notifications In Your App? With the fame that Flutter has garnered over the years, it has become the top choice of business owners for cross-platform mobile app development. With the enhancement of features like push notifications, it has further made its place
  • 5. STEP 1: Set up and create a new Firebase project ● Log in to your Google account and access the Firebase console. ● Click “Add Project”, enter the project name, and click “Continue”. ● Next, disable Google Analytics and click “Create Project”. The Firebase Project will be created. ● Once the project is initialized, click “Continue” to land on the Project Overview Screen.
  • 6.
  • 7. STEP 2: Integrate the Firebase Project with your Android App ● Firstly, create a Flutter application using the command “flutter create notify” and open it in your IDE. ● Now, click on the Android icon, shown on the Project Overview Screen and it will direct you to a form. ● Fill in the following details: Android package name (get it from the following path project directory → android → app → src → main → AndroidManifest.xml). Next, enter a nickname for your app (optional).
  • 8. Enter SHA-1 hash (click on the help icon to know where to get the SHA-1 hash value)
  • 9. ● Click “Register app” and your app will be registered. ● Next, download the google-services.json file, drag and drop it to the following path project directory → android → app, and click “Next”. ● Add Firebase SDK using the code snippet below and click “Next”. buildscript { repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository }
  • 10. dependencies { ... // Add this line classpath 'com.google.gms:google-services:4.3.4' } } allprojects { ... repositories {
  • 11. google() // Google's Maven repository ... } } ● Now, apply google-plugin-services to the Gradle files. ● Lastly, click “Continue to console” and your Firebase set-up for the Android app will be completed.
  • 12. STEP 3: Install Firebase Plugins With the help of firebase cloud messaging, the most important step for adding Push Notifications is explained below, follow carefully. There are three plugins required for this sample project, which are: ● firebase_core: Helps in using Firebases service with the Flutter app. ● firebase_messaging: Helps in receiving notifications in the Flutter app. ● overlay_support: Helps in building overlay UI.
  • 13.
  • 14. To add these packages to your project: ● Get their latest version from the pub.dev. ● Add these packages to the pubspec.yaml file of your Flutter Project using the command below: flutter pub add firebase_core //installs firebase core flutter pub add firebase_messaging //installs firebase massaging package flutter pub add overlay_support //installs overlay support ● Look for dependencies in the pusbspec.yaml file. The added dependencies should be:
  • 15. dependencies: firebase_core: ^1.13.1 firebase_messaging: ^11.2.11 overlay_support: ^1.2.1 STEP 4: Create a UI for Flutter App and Add Push Notification Functionality It is per your convenience and interest that you can build a Flutter UI. Here, I have purposely skipped the details for UI creation as I want to focus on the Push Notification functionality of the app.
  • 16. ● The first step here is to define a variable for FirebaseMessaging. For that, run the following command: class _HomePageState extends State { late final FirebaseMessaging _messaging; // ... @override Widget build(BuildContext context) { // ... }
  • 17.
  • 18. ● Then, create a method as registerNotification() inside the class _HomePageState. This helps in initializing the Firebase app and instantiating Firebase Messaging. void registerNotification() async { // 1. Initialize the Firebase app await Firebase.initializeApp(); // 2. Instantiate Firebase Messaging _messaging = FirebaseMessaging.instance;
  • 19. ● Now, to receive a Push Notification on your device and make changes in the UI, run the command below: void registerNotification() async { //... if (settings.authorizationStatus == AuthorizationStatus.authorized) { print('User granted permission'); // For handling the received notifications
  • 20. { // Parse the message received PushNotification notification = PushNotification( title: message.notification?.title, body: message.notification?.body, ); setState(() { _notificationInfo = notification; _totalNotifications++;
  • 21. }); } else { print('User declined or has not accepted permission'); } } By now you must be aware of the fact that PushNotification is a model class that stores notification content. It should look like this:
  • 22.
  • 23. Step 5: Sending Push Notification in your Flutter app If you got to step 3, you will find we have used an overlays-support plugin. This comes into action now. Here we will show how firebase cloud messaging has made it easy for you to receive the notifications while: 1. the app is in use 2. the app is in minimized state 3. App is in a closed state
  • 24. When App is in use
  • 25. ● Now, you can create a sample or a custom UI effect for Push Notification when it arrives on your device. class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return OverlaySupport( child: MaterialApp( // ... ),
  • 26. } } ● Now to display the Push Notification inside your app use the function showSimpleNotification(). void registerNotification() async { //… if (settings.authorizationStatus == AuthorizationStatus.authorized) {
  • 27. { // ... if (_notificationInfo != null) { // For displaying the notification as an overlay showSimpleNotification( Text(_notificationInfo!.title!), leading: NotificationBadge(totalNotifications: _totalNotifications), subtitle: Text(_notificationInfo!.body!),
  • 28. duration: Duration(seconds: 2), ); } }); } else { print('User declined or has not accepted permission'); } }
  • 29. ● Next, you have to use two variables to display the notification information, namely, _notificationInfo and _totalNotifications. class _HomePageState extends State { late int _totalNotifications; PushNotification? _notificationInfo; //… @override Widget build(BuildContext context) { return Scaffold(
  • 30. appBar: AppBar( title: Text('Notify'), brightness: Brightness.dark, ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ //...
  • 31. _notificationInfo != null ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'TITLE: ${_notificationInfo!.title}', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16.0,
  • 32. ), SizedBox(height: 8.0), Text( 'BODY: ${_notificationInfo!.body}', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16.0, ), ),
  • 33. ) : Container(), ], ), ); } } Shown above is a column with the two text widgets i.e., notification title and body.
  • 34. When App is in Minimized State
  • 35. ● To handle Push Notifications while the app is in terminated state, we need to define a top-level function. This function _firebaseMessagingBackgroundHandler(), should not be included in any of the classes defined Firstly, define the above function as shown below: Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async { print("Handling a background message: ${message.messageId}"); }
  • 36. Now, call the method onBackgroundMessage(). void registerNotification() async { await Firebase.initializeApp(); _messaging = FirebaseMessaging.instance; // Add the following line FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackground Handler); // ... } ● If your app is running in the background and you tapped on the received notification, then this action needs to be handled using the initState()
  • 37. @override void initState() { //... // For handling notification when the app is in background // but not terminated FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { PushNotification notification = PushNotification( title: message.notification?.title, body: message.notification?.body, ); setState(() {
  • 39. When App is in Closed State
  • 40. As we know, Push Notifications can also be sent while the app is in the terminated state. So, let’s see what commands we need to run while we open the notification in the app’s closed state. For this, the first step is to define checkForInitialMessage() in this method. // For handling notification when the app is in terminated state checkForInitialMessage() async { await Firebase.initializeApp(); RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
  • 41. if (initialMessage != null) { PushNotification notification = PushNotification( title: initialMessage.notification?.title, body: initialMessage.notification?.body, ); setState(() { _notificationInfo = notification; _totalNotifications++; });
  • 42. } Next, call this method, for iniState method(). @override void initState() { // ... // Call here checkForInitialMessage(); // ...
  • 43. } STEP 6: Sample Testing of Flutter Push Notifications on Android Device In order to run this app on an Android device, follow the steps below. ● Go to android → app → build.gradle and enable multidex support, using the command: android { defaultConfig { // ... multiDexEnabled true
  • 44. ● Add <intent-filter> tag inside <activity> (follow this path android → app → src → main → AndroidManifest.xml). This tag will help you in retrieving the message at the time of notification’s arrival. <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="<your_package_name>"> <application android:label="notify" android:icon="@mipmap/ic_launcher">
  • 45. android:name=".MainActivity" <!-- ... --> <!-- Add this tag --> <intent-filter> <action android:name="FLUTTER_NOTIFICATION_CLICK" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
  • 46. <!-- ... --> </application> </manifest> You can also add additional messages using Firebase console. This way you can add Push Notifications using firebase cloud messaging in Flutter apps.