Quick Summary

With the efficiently evolving tech development marketplace, keeping in touch with the users is a significant part of ensuring optimal results for your business application development. Push notifications are of the essence to engage users, encourage retention, and improve the overall experience of your business application for your end-users. Flutter Push Notifications with Firebase Cloud Messaging offers a smooth way to integrate cloud notifications within your business applications. In this blog post, we initially understand Push Notifications and their benefits. Also, we will discuss the steps to implement Push Notifications with Firebase Cloud Messaging for your next development project.

Table of Contents

What are Push notifications?

Push Notifications are brief messages or alerts mobile applications send to users’ devices. These notifications pop up on the user’s lock screen, notification center, or status bar, letting users know about your business application’s latest updates, messages, events, or reminders. These are of the essence for keeping your users engaged and informed, even if they are not currently using mobile applications. The Push notifications keep their users interested in the app and improve the overall experience, giving them timely and valuable information on their devices.

Benefits of Push Notifications!

Push notifications are a crucial part of our day-to-day activities. When used correctly, they bring many benefits.

  • Improves User Engagement: Push notifications keep users engaged with the app more by sending helpful content and updates.
  • Improves Retention Rate: Retaining an existing customer is always easier than acquiring a new one. Push notifications help increase the probability of a high click and open rate.
  • Increase Conversions: Timed and relevant push notifications can help increase conversions by creating interest and urgency among users.
  • Keeps The User Updated: You can increase users’ likelihood of using the app by reminding them why it is good and offering them special deals or updates.
  • Channel User Preferences: If you send notifications at the right time, users are likelier to do what they want, like buy something, finish a task, or return to the app.
  • Make Users Happy: When notifications are personal and helpful, they make users feel like you care about them, which makes their overall experience better.

Flutter and Firebase Cloud Messaging

Flutter makes building mobile applications easier by combining many useful features and having a strong community to help. When you use Flutter along with Firebase Cloud Messaging (FCM), adding cloud notifications to your application becomes a breeze.

Key Benefits of Using FCM with Flutter:

  • Easy to Add: Flutter works smoothly with Firebase, so adding FCM to your application does not take much effort.
  • Works Everywhere: FCM supports Android and iOS, so your push notifications will work simultaneously on different devices.
  • You Get Useful Data: Firebase Analytics gives you helpful information about how users behave and how your notifications perform. This information helps you improve your notifications.
  • Messages Always Get Through: The FCM Flutter ensures your notifications are reliably delivered even if the network isn’t great.

Prerequisites

Before diving into the setup process, make sure you have the following prerequisites in place for implementing Flutter Push Notifications with Firebase Cloud Messaging:

Get Ready To Scale Your Business Application With The Power Of The Flutter Framework.

Hire Flutter developer from us to easily build robust and performant cross-platform applications.

Create a Firebase Project

Now, when you have logged in to the Firebase console, create a new project by clicking on the ‘Add Project’ button.

Create a Firebase Project

After creating the project, you will be redirected to the project dashboard. For a detailed setup guide on registering Android / iOS apps to Firebase, please refer to our previous blog, Firebase Setup Guide.

Once Firebase has been set up and you have successfully registered your Android and/or iOS apps with Firebase, let’s start with our cloud messaging setup to help us control Push notifications.

Setting up the FutterFire Plugin

FlutterFire is the set of Flutter plugins that enable Flutter apps to use Firebase services. To integrate Firebase Cloud Messaging with your Flutter app:

Add the firebase_messaging plugin by running the following command in your terminal:

Copy Text
flutter pub add firebase_messaging

Configure Firebase Messaging for the Mobile App

Now, we must configure our iOS and Android for Flutter push notifications with Firebase.

iOS

Let us start with iOS push notifications with Firebase, which you can achieve using the steps given below:

Enabling App Capabilities

  • To receive push and background notifications in iOS, we need to enable the background capabilities in the Xcode project workspace.
  • Open the Xcode project workspace for your flutter project (flutter_app_directory/iOS/.Runner.xcworkspace).
Enabling App Capabilities
  • Once the XCode project is open, enable the ‘Push Notifications’, and ‘Background Modes’ from capabilities.
  • Enable Background Fetch and Remote notifications under Background Modes.
  • Background Fetch and Remote notifications

    Registering Our iOS App To The Apple Developer Account

    • We have completed the notifications setup from XCode, but we must register our bundle identifier and enable push notifications in our Apple developer account.
    Register An Apple ID
    • After enabling the push notifications from the developer account, we must create and download a sandbox push notification certificate.
    Apple Push Notification Services
    • Once you have downloaded the certificate, double-click on it to open it in the keychain. After opening the certificate, export it into the .p12 extension.
    Certificates

    Uploading APN Certificate to Firebase

    • We have to upload the exported certificate to Firebase to start receiving notifications.
    • Open the Firebase console and go to Project settings ➡️ Cloud messaging ➡️ APNs Certificates.
    Firebase console
    • Upload the exported .p12 certificate in APN certificates.
    Upload .p12 certificate in APN certificates.
    • Now, we have completed the iOS setup for Cloud Messaging.

    Android

    We must follow the steps below to ensure the setup for Android push notifications Firebase.

    • We must add the notification channel ID in our AndroidManifest.xml file for the Android side configuration.
    • Add the following code in your AndroidManifest.xml file under the main activity tag.
    Copy Text
    <meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="high_importance_channel"  />
    Copy Text
    <intent-filter>
                    <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                    <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    • We have completed the Android setup for Cloud Messaging.

    Handle Incoming Notifications

    The next step is to handle the incoming notifications, for which you have to follow the process given below:

    Initial Setup for Receiving Notifications

    Now, we have to handle the notifications on the application side, as we have completed the setup to receive them. We will create a notification_service that will handle all the notification-related code.

    Let’s start by creating notifications_service.dart

    Copy Text
    class NotificationService {
             ///single instance of FCM
             static final _messaging = FirebaseMessaging.instance;
    
             ///To store the FCM token
             static String? _token;
     }

    We have created a static instance of the FirebaseMessaging object and also for the FCM token that we will be receiving from Firebase.

    FCM Token is a unique identifier for the device that sends notifications to that device.

    So, for that purpose, we need to store the FCM token.

    Let’s add a function that will ask the user for notification permission. After the Android 13 update, it is possible to ask the notification permission in runtime.

    Copy Text
    ///ask permission from the user to display notifications
      static void _requestPermission() async {
        final settings = await _messaging.requestPermission(
          alert: true,
          announcement: false,
          badge: true,
          carPlay: false,
          criticalAlert: false,
          provisional: false,
          sound: true,
        );
    
        if (settings.authorizationStatus == AuthorizationStatus.authorized) {
          /// User has granted the notification permission
        } else if (settings.authorizationStatus ==
            AuthorizationStatus.provisional) {
          /// User has only granted the provisional permission
        } else {
          /// User has discarded the permission popup or denied the notification permission
        }
      }

    Now, let’s fetch the FCM token.

    Copy Text
    ///setup the FCM token to receive notifications
      static void _getFCMToken() async {
        _token = await _messaging.getToken();
    
        ///onTokenRefresh stream allows us to listen to the token value whenever it changes
        _messaging.onTokenRefresh.listen((newValue) {
          _token = newValue;
        });
      }

    Note: If you encounter the following error given below:

    Copy Text
    uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library [:firebase_messaging]

    Follow the instructions after the error and provide the higher minSkVersion in the app-level build.gradle file(android/app/build.gradle), which in our case is 19

    Handling Foreground Notifications

    Notifications that are received when the app is open and is being used are referred to as foreground notifications.

    We must use the Flutter local notifications plugin to handle and display the foreground notifications. If you want to display a notification in the foreground, you can use the data sent along with it and set the logic accordingly.

    Add the Flutter local notifications plugin.

    Copy Text
    flutter pub add flutter_local_notifications

    Let’s create a notification plugin instance and notification channels that will be used to display notifications.

    Copy Text
    ///notification plugin initialisation
      static final FlutterLocalNotificationsPlugin
          _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    
      ///notification channel to handle android notifications
      static const AndroidNotificationChannel _androidNotificationChannel =
          AndroidNotificationChannel(
        'high_importance_channel',
        'High Importance Notifications',
        description: 'This channel is used for important notifications.',
        importance: Importance.max,
      );
    
      ///notification channel to handle iOS notifications
      static const DarwinNotificationDetails _iOSNotificationChannel =
          DarwinNotificationDetails(
        presentAlert: true,
        presentBadge: true,
        presentSound: true,
      );

    Now, let’s create a function to configure the Flutter local notifications plugin. This function will initialize the local notifications plugin with Android and iOS settings.

    Copy Text
    static void _configureLocalNotificationPlugin() async {
     const AndroidInitializationSettings initializationSettingsAndroid =
         AndroidInitializationSettings('ic_launcher');
    
     const DarwinInitializationSettings initializationSettingsIOS =
         DarwinInitializationSettings(
       requestSoundPermission: false,
       requestBadgePermission: false,
       requestAlertPermission: false,
     );
    
     await _flutterLocalNotificationsPlugin.initialize(
       const InitializationSettings(
         android: initializationSettingsAndroid,
         iOS: initializationSettingsIOS,
       ),
       onDidReceiveNotificationResponse: (response) {},
     );
    
     /** Update the iOS foreground notification presentation options to allow
      heads up notifications. */
     await _messaging.setForegroundNotificationPresentationOptions(
       alert: true,
       badge: true,
       sound: true,
     );
    }

    Further, we must create the Android notification channels with the properties defined in the _androidNotificationChannel variable declared in the function scope.

    Copy Text
    static void _createAndroidNotificationChannel() async {
        /** we have created the android notification channel which
          we had specified in the AndroidManifest.xml file earlier */
        await _flutterLocalNotificationsPlugin
            .resolvePlatformSpecificImplementation<
                AndroidFlutterLocalNotificationsPlugin>()
            ?.createNotificationChannel(_androidNotificationChannel);
      }

    Now that we have completed all the setups required to receive the notification, we will create a function that will handle the display of the foreground notification and its click.

    Copy Text
    static void _showForegroundNotification(RemoteMessage message) async {
        RemoteNotification? notification = message.notification;
        if (notification != null) {
          _flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                _androidNotificationChannel.id,
                _androidNotificationChannel.name,
                channelDescription: _androidNotificationChannel.description,
                icon: 'launch_background',
              ),
              iOS: _iOSNotificationChannel,
            ),
          );
        }
      }

    Most of the notification part is completed. We need to add a foreground notification listener during the notification service initialization, which we will do later when we complete the background notification setup.

    Handling Background Notifications

    Notifications received when the application is in the recent applications tray or dead state are referred to as background notifications.

    We do not have much control over displaying notifications as they are automatically added to the system’s notifications queue. However, we can modify the default behavior by omitting the notification variable in the remote message object that is received from the firebase.

    We want to display the notification received for now, so we will set the background handling accordingly.

    First, we need to add a background message handler in our main.dart following three simple criteria:

    • It must not be an anonymous function.
    • It must be a top-level function.
    • When using Flutter version 3.3.0 or higher, the message handler must be annotated with @pragma(‘vm:entry-point’) above the function declaration (otherwise, it may be removed during tree shaking for release mode).
    Copy Text
    @pragma('vm:entry-point')
    Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
     /** If we are going to use further Firebase services we need to
      * initialize the Firebase setup
      */
     await firebaseInitialisation();
    }
    
    void main() async {
     WidgetsFlutterBinding.ensureInitialized();
     FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
     await firebaseInitialisation();
     runApp(const FirebaseMessagingDemo());
    }

    After registering the background message handler, we must define a function in the notification service class that will be called when the notification is clicked.

    Copy Text
    static void _handleBackgroundNotificationOnTap(RemoteMessage message) async {
        RemoteNotification? notification = message.notification;
        if (notification != null) {
          debugPrint('Notification clicked: ${notification.title}');
          // You can put your logic here to handle the notification on click
        }
      }

    Initializing the Notification Service

    We have completed all the steps to receive and display notifications. Now, we have to initialize our notifications service to start handling notifications.

    Let’s create an init function in the notification service class.

    Copy Text
    static Future init() async {
        _requestPermission();
        _getFCMToken();
        _configureLocalNotificationPlugin();
        _createAndroidNotificationChannel();
    
        /// Foreground notification handler
        FirebaseMessaging.onMessage.listen(_showForegroundNotification);
    
        /// Background notification handler
        FirebaseMessaging.onMessageOpenedApp
            .listen(_handleBackgroundNotificationOnTap);
      }
    

    This init function has the initializing calls necessary to display and interact with our notifications.

    Now, we will call this init function in our main.dart file to initialize the notification service.

    Copy Text
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
      await _firebaseInitialisation();
      await NotificationService.init();
      runApp(const FirebaseMessagingDemo());
    }

    We have successfully completed the setup for the push notifications we will receive from Firebase cloud messaging (FCM). Let’s test this setup and send some notifications from the Firebase console.

    Testing Cloud Notifications

    To test the cloud notifications, we will send the notification from the Firebase console to the app. Let’s create our first campaign for Firebase notification messages and test them on our device.

    Go Firebase console ➡️ Messaging ➡️ Create your first campaign.

    Testing Cloud Notifications

    Select the Firebase notification message and click on Create.

    After that, Enter the notification title and text and click Next.

    Enter the notification title and text

    Select the preferred target to continue and click on Next.

    Select the preferred target user to continue

    In schedule, select now and click on Next. Skip the optional Conversion events and Additional options and click on Review.

    Additional Options

    Now, publish the notification campaign.

    Publish the Notification Campaign

    After the campaign is published, the notification should appear on the device. To explore the full potential of Firebase Cloud Messaging, try sending out multiple notifications enabling different data content within the campaign.

    For more detailed info, refer to this GitHub repository for complete code.

    Conclusion

    Following these steps, you can easily set up cloud notifications in your Flutter applications using Flutter Cloud Messaging. Push notifications are a powerful tool for engaging users, delivering timely updates, and enhancing the overall user experience. As a business owner, if you are confused about making the right call to introduce Flutter Push Notifications with Firebase Cloud Messaging, you can contact a leading Flutter app development company like Bacancy and get started today with your development process while you focus on your core business.

Fuel Your Success With Exceptional Flutter Cross-Platform Apps

Contact Us

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?