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 firmly in the world of app development. In this blog, I will help you understand firebase cloud messaging by showing the procedure of adding Push Notification in a Flutter app for android with the help of a sample project. Let’s discuss the steps that need to be executed for this phenomenal integration.
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
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
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!),
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(
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(() {
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();
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.