Push Notifications: How to add them to a Flutter App

Jul 05, 2022

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 notification 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 in your app.

Before getting into detail of how to add push notifications using Flutter, let's have a quick look as to what are its benefits.

  • Increases user retention i.e. a greater number of users download the app
  • Increases user engagement in the app
  • Significant increase in the conversion rate
  • Keeps track of user metrics
  • Improved user experience

Now, let’s have a look at the steps to add push notifications in your app.

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 firm 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.

STEP 1: Set up and create a new Firebase project

  • Log in to your Google account and access 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 Android icon, shown on the Project Overview Screen and it will direct you to a form.
  • Fill in the following details:
    Andoid pacakge name (get it from the following path project directory → android → app → src → main → AndroidManifest.xml).
    Next, enter a nick name for your app (optional).
    Enter SHA-1 hash (click on the help icon to know where to get SHA-1 hash value)
  • Click “Register app” and your app will be registered.
  • Next, download 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 {
   // Check that you have the following line (if not, add it):
   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 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 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 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 as 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, in order 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
       FirebaseMessaging.onMessage.listen((RemoteMessage message) {
         // 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 and overlays-support plugin. This comes into action now. Here we will show how firebase cloud messaging has made it easy to for you to receive the notifications while the:

  • App is in use
  • App is in minimized state
  • App is in 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 in order to display the Push Notification inside your app use the function showSimpleNotification().
    void registerNotification() async {
     //...

     if (settings.authorizationStatus == AuthorizationStatus.authorized) {
       FirebaseMessaging.onMessage.listen((RemoteMessage message) {
         // ...
         if (_notificationInfo != null) {
           // For displaying the notification as an overlay
           showSimpleNotification(
             Text(_notificationInfo!.title!),
             leading: NotificationBadge(totalNotifications: _totalNotifications),
             subtitle: Text(_notificationInfo!.body!),
             background: Colors.cyan.shade700,
             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

In order 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(_firebaseMessagingBackgroundHandler);

 // ...
}

If your app is running in the background and you tapped on the received notification, then this action needs to be handled using initState() method.
@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(() {
     _notificationInfo = notification;
     _totalNotifications++;
   });
 });

 super.initState();
}

When App is in Closed State

As we know, Push Notifications can also be sent while the app is in 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() 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();

 // ...
 super.initState();
}

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">
       <activity
           android:name=".MainActivity"
           <!-- ... -->
           <!-- Add this tag -->
           <intent-filter>
             <action android:name="FLUTTER_NOTIFICATION_CLICK" />
             <category android:name="android.intent.category.DEFAULT" />
           </intent-filter>
       </activity>
       <!-- ... -->
   </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. This is one of the most popular features in mobile apps these days and we at Fibonalabs always strive to stay hand in hand with the latest technologies. With the help of their excellent skillset our developers work on developing the most efficient and productive mobile apps as well as web apps. Our skillful UX/UI designers further add the feather in the cap. Visit us at www.fibonalabs.com to avail the best of our services.

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.