SlideShare a Scribd company logo
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

More Related Content

What's hot

OpenCVでつくろうARスタンプアプリ in 熊本
OpenCVでつくろうARスタンプアプリ in 熊本OpenCVでつくろうARスタンプアプリ in 熊本
OpenCVでつくろうARスタンプアプリ in 熊本
Takashi Yoshinaga
 
Media Art II 2013 第5回:openFrameworks Addonを使用する
Media Art II 2013 第5回:openFrameworks Addonを使用するMedia Art II 2013 第5回:openFrameworks Addonを使用する
Media Art II 2013 第5回:openFrameworks Addonを使用するAtsushi Tadokoro
 
Flutter session 01
Flutter session 01Flutter session 01
Flutter session 01
DSC IEM
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
Geshan Manandhar
 
Data Modeling with NGSI, NGSI-LD
Data Modeling with NGSI, NGSI-LDData Modeling with NGSI, NGSI-LD
Data Modeling with NGSI, NGSI-LD
Fernando Lopez Aguilar
 
デジタルアートセミナー#2 openFrameworksで学ぶ、 クリエイティブ・コーディング Session 2: 構造をつくる
デジタルアートセミナー#2 openFrameworksで学ぶ、 クリエイティブ・コーディング Session 2: 構造をつくるデジタルアートセミナー#2 openFrameworksで学ぶ、 クリエイティブ・コーディング Session 2: 構造をつくる
デジタルアートセミナー#2 openFrameworksで学ぶ、 クリエイティブ・コーディング Session 2: 構造をつくるAtsushi Tadokoro
 
Flutter festival - Write your first Flutter application
Flutter festival - Write your first Flutter applicationFlutter festival - Write your first Flutter application
Flutter festival - Write your first Flutter application
Apoorv Pandey
 
Intro to GitOps & Flux.pdf
Intro to GitOps & Flux.pdfIntro to GitOps & Flux.pdf
Intro to GitOps & Flux.pdf
Weaveworks
 
ROS/ROS2 Distributed System with Kubernetes
ROS/ROS2 Distributed System with KubernetesROS/ROS2 Distributed System with Kubernetes
ROS/ROS2 Distributed System with Kubernetes
Tomoya Fujita
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
Henry Schreiner
 
Unity ネイティブプラグインの作成について
Unity ネイティブプラグインの作成についてUnity ネイティブプラグインの作成について
Unity ネイティブプラグインの作成についてTatsuhiko Yamamura
 
Nreal Lightハンズオン
Nreal LightハンズオンNreal Lightハンズオン
Nreal Lightハンズオン
Takashi Yoshinaga
 
Terraform on Azure
Terraform on AzureTerraform on Azure
Terraform on Azure
Mithun Shanbhag
 
ネットワーク自動化、なに使う? ~自動化ツール紹介~(2017/08/18追加開催)
ネットワーク自動化、なに使う? ~自動化ツール紹介~(2017/08/18追加開催) ネットワーク自動化、なに使う? ~自動化ツール紹介~(2017/08/18追加開催)
ネットワーク自動化、なに使う? ~自動化ツール紹介~(2017/08/18追加開催)
akira6592
 
Terraform
TerraformTerraform
Terraform
Phil Wilkins
 
Everything You Need To Know About Persistent Storage in Kubernetes
Everything You Need To Know About Persistent Storage in KubernetesEverything You Need To Know About Persistent Storage in Kubernetes
Everything You Need To Know About Persistent Storage in Kubernetes
The {code} Team
 
Container Security
Container SecurityContainer Security
Container Security
Jie Liau
 
Terraform: Infrastructure as Code
Terraform: Infrastructure as CodeTerraform: Infrastructure as Code
Terraform: Infrastructure as Code
Pradeep Bhadani
 
Block join toranomaki
Block join toranomakiBlock join toranomaki
Block join toranomaki
Ebisawa Shinobu
 
Writing Custom Python Detection with Panther (Part 1)
Writing Custom Python Detection with Panther (Part 1)Writing Custom Python Detection with Panther (Part 1)
Writing Custom Python Detection with Panther (Part 1)
Panther Labs
 

What's hot (20)

OpenCVでつくろうARスタンプアプリ in 熊本
OpenCVでつくろうARスタンプアプリ in 熊本OpenCVでつくろうARスタンプアプリ in 熊本
OpenCVでつくろうARスタンプアプリ in 熊本
 
Media Art II 2013 第5回:openFrameworks Addonを使用する
Media Art II 2013 第5回:openFrameworks Addonを使用するMedia Art II 2013 第5回:openFrameworks Addonを使用する
Media Art II 2013 第5回:openFrameworks Addonを使用する
 
Flutter session 01
Flutter session 01Flutter session 01
Flutter session 01
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Data Modeling with NGSI, NGSI-LD
Data Modeling with NGSI, NGSI-LDData Modeling with NGSI, NGSI-LD
Data Modeling with NGSI, NGSI-LD
 
デジタルアートセミナー#2 openFrameworksで学ぶ、 クリエイティブ・コーディング Session 2: 構造をつくる
デジタルアートセミナー#2 openFrameworksで学ぶ、 クリエイティブ・コーディング Session 2: 構造をつくるデジタルアートセミナー#2 openFrameworksで学ぶ、 クリエイティブ・コーディング Session 2: 構造をつくる
デジタルアートセミナー#2 openFrameworksで学ぶ、 クリエイティブ・コーディング Session 2: 構造をつくる
 
Flutter festival - Write your first Flutter application
Flutter festival - Write your first Flutter applicationFlutter festival - Write your first Flutter application
Flutter festival - Write your first Flutter application
 
Intro to GitOps & Flux.pdf
Intro to GitOps & Flux.pdfIntro to GitOps & Flux.pdf
Intro to GitOps & Flux.pdf
 
ROS/ROS2 Distributed System with Kubernetes
ROS/ROS2 Distributed System with KubernetesROS/ROS2 Distributed System with Kubernetes
ROS/ROS2 Distributed System with Kubernetes
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
Unity ネイティブプラグインの作成について
Unity ネイティブプラグインの作成についてUnity ネイティブプラグインの作成について
Unity ネイティブプラグインの作成について
 
Nreal Lightハンズオン
Nreal LightハンズオンNreal Lightハンズオン
Nreal Lightハンズオン
 
Terraform on Azure
Terraform on AzureTerraform on Azure
Terraform on Azure
 
ネットワーク自動化、なに使う? ~自動化ツール紹介~(2017/08/18追加開催)
ネットワーク自動化、なに使う? ~自動化ツール紹介~(2017/08/18追加開催) ネットワーク自動化、なに使う? ~自動化ツール紹介~(2017/08/18追加開催)
ネットワーク自動化、なに使う? ~自動化ツール紹介~(2017/08/18追加開催)
 
Terraform
TerraformTerraform
Terraform
 
Everything You Need To Know About Persistent Storage in Kubernetes
Everything You Need To Know About Persistent Storage in KubernetesEverything You Need To Know About Persistent Storage in Kubernetes
Everything You Need To Know About Persistent Storage in Kubernetes
 
Container Security
Container SecurityContainer Security
Container Security
 
Terraform: Infrastructure as Code
Terraform: Infrastructure as CodeTerraform: Infrastructure as Code
Terraform: Infrastructure as Code
 
Block join toranomaki
Block join toranomakiBlock join toranomaki
Block join toranomaki
 
Writing Custom Python Detection with Panther (Part 1)
Writing Custom Python Detection with Panther (Part 1)Writing Custom Python Detection with Panther (Part 1)
Writing Custom Python Detection with Panther (Part 1)
 

Similar to Push Notifications: How to add them to a Flutter App

Cloud Messaging Flutter
Cloud Messaging FlutterCloud Messaging Flutter
Cloud Messaging Flutter
MuhammadAli408757
 
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...
naseeb20
 
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
 
Firebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript AppsFirebase Push Notification in JavaScript Apps
Firebase Push Notification in JavaScript Apps
Inexture Solutions
 
Email authentication using firebase auth + flutter
Email authentication using firebase auth + flutterEmail authentication using firebase auth + flutter
Email authentication using firebase auth + flutter
Katy Slemon
 
Build Location Based App on bada
Build Location Based App on badaBuild Location Based App on bada
Build Location Based App on bada
Cheng Luo
 
Android 103 - Firebase and Architecture Components
Android 103 - Firebase and Architecture ComponentsAndroid 103 - Firebase and Architecture Components
Android 103 - Firebase and Architecture Components
Kai Koenig
 
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
valuebound
 
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...
InnovationM
 
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
Concetto Labs
 
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
BradSmith250819
 
What is new in Firebase?
What is new in Firebase?What is new in Firebase?
What is new in Firebase?
Sinan Yılmaz
 
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
Ajay Chebbi
 
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
ShepHertz
 
Firebase
FirebaseFirebase
Dense And Hot Web Du
Dense And Hot  Web DuDense And Hot  Web Du
Dense And Hot Web Du
michael.labriola
 
Sencha Touch MVC
Sencha Touch MVCSencha Touch MVC
Sencha Touch MVC
Neha Upadhyay
 
Local Notification Tutorial
Local Notification TutorialLocal Notification Tutorial
Local Notification Tutorial
Ketan Raval
 
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...
ShepHertz
 
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
TMME - TECH MEETUP FOR MYANMAR ENGINEERS IN JP
 

Similar to 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
 

More from Fibonalabs

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
Fibonalabs
 
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
Fibonalabs
 
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?
Fibonalabs
 
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
Fibonalabs
 
Simplifying CRUD operations using budibase
Simplifying CRUD operations using budibaseSimplifying CRUD operations using budibase
Simplifying CRUD operations using budibase
Fibonalabs
 
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
Fibonalabs
 
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
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
Fibonalabs
 
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
Fibonalabs
 
10 Heuristic Principles
10 Heuristic Principles10 Heuristic Principles
10 Heuristic Principles
Fibonalabs
 
Key Skills Required for Data Engineering
Key Skills Required for Data EngineeringKey Skills Required for Data Engineering
Key Skills Required for Data Engineering
Fibonalabs
 
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
Fibonalabs
 
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
Fibonalabs
 
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...
Fibonalabs
 
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
Fibonalabs
 
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
Fibonalabs
 
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
Fibonalabs
 
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...
Fibonalabs
 
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
Fibonalabs
 
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
Fibonalabs
 

More from 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
 

Recently uploaded

FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 

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.