Firebase Integration

Integrate FireBase to the Application#

Step 1: Create Project in the firebase console using your app package name. Ex: com.testapp

Step 2: After the project creation download the google-service.json and GoogleService-Info.plist file which is automatically generated.

Step 3: Add the google-service.json file to your android/app Folder.

Step 4: Add the GoogleService-Info.plist file to your iOS/Runner Folder.

Step 5: Add the firebase dependencies in the pubspec.yaml file.

dependencies:
firebase_core: ^latest_version
firebase_messaging: ^latest_version

Step 6: Run flutter pub get to install the dependencies.

Initialize Firebase in Your App#

Step 1: In your main.dart file, initialize Firebase in the main function.

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

Step 2: Configure FCM in Your App

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
//Configuring FCM to Handle Incoming Messages
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// Handle background messages
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
// We are checking the Platform Condition here, because we are handling the push notification in iOS via Notification Extension
if (Platform.isAndroid) {
//Handle the push notification as given below
onMessage(message);
}
}

Handle Notification#

Upon receiving a Firebase push notification in your Firebase Messaging service, you can utilize the following method to retrieve the notification content and subsequently create and display the notification.

static void onMessage(RemoteMessage message) {
WidgetsFlutterBinding.ensureInitialized();
await Mirrorfly.handleReceivedMessage(notificationData).then((value) async {
var data = chatMessageFromJson(value.toString());
if(data.messageId!=null) {
//Create and Display the Notification
}
});
}

Note: For push notifications in iOS, certain limitations exist when the app is in the terminated or background state. Therefore, we utilize the Notification Service Extension to handle these push notifications.

Additional Configuration For iOS#

For iOS, additional configuration is required to enable push notifications. This includes adding specific settings and a notification extension to ensure that push notifications are received in the background and terminated states.

Note: Please upload your APNS and VOIP Certificate to our Console. To know more how to generate and upload APNS and VOIP Certificate Click Here

Capabilities#

To receive push notification in the background or in the killed state, You need to enable below capabilities.

Next the "Push Notifications" capability needs to be added to the project. This can be done via the "Capability" option on the "Signing & Capabilities" tab:

Step 1: Click on the "+ Capabilities" button.

Step 2: Search for "Push Notifications".

PushNotification1

Next the "Background Modes" capability needs to be enabled, along with both the "Background fetch" and "Remote notifications" sub-modes. This can be added via the "Capability" option on the "Signing & Capabilities" tab:

Step 1: Click on the "+ Capabilities" button.

Step 2: Search for "Background Modes".

PushNotification2

Now ensure that both the "Background fetch" and the "Remote notifications" sub-modes are enabled:

PushNotification3

App Group Id#

To receive messages in the background or in the killed state, You need to enable app group container ID.

In order to access data between app and notification extension, enabling app group is mandatory to access user defaults and database in container.

Capabilities

caution

Need to use Same App Group Id in both Targets Runner and Notification Extension

Notification Extension#

As a process of getting push notification in background and Killed state, the SDK require to add Notification Extension service in your project.

Notification service extension can be acts as a mediator between the User Interface and the APNS. Like all other iOS extensions, such an extension can simply be added to the app in the form of another target.

Step 1: To Create NotificationExtension Target, Open iOS Folder in Xcode

In Xcode -> File -> New -> Target -> ' NotificationServiceExtension' -> Next -> TargetName -> Activate Scheme

PushNotification5

Step 2: Add Firebase Messaging and Mirrorfly Plugin to the new target created for NotificationExtension in Podfile

target 'NotificationExtension' do
use_frameworks!
pod 'Firebase/Messaging'
pod 'mirrorfly_plugin', :path => '.symlinks/plugins/mirrorfly_plugin/ios'
end

Step 3: Do pod install from Terminal inside ios folder.

Step 4: Import Mirrorfly Plugin in Notification Extension File

import mirrorfly_plugin

Step 5: Inside the didReceive function in the notification extension file, add the following code. This code will handle the incoming push notifications.

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
MirrorFlyNotification().handleNotification(notificationRequest: request, contentHandler: contentHandler, containerID: APPGROUPS, licenseKey: LICENSEKEY)
}

Requesting permission#

The firebase_messaging package provides a simple API for requesting permission via the requestPermission method.

FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: true,
sound: true,
);
print('User granted permission: ${settings.authorizationStatus}');
PermissionDefaultDescription
alerttrueSets whether notifications can be displayed to the user on the device.
announcementfalseIf enabled, Siri will read the notification content out when devices are connected to AirPods.
badgetrueSets whether a notification dot will appear next to the app icon on the device when there are unread notifications.
carPlaytrueSets whether notifications will appear when the device is connected to CarPlay.
provisionalfalseSets whether provisional permissions are granted. See Provisional authorization for more information.
soundtrueSets whether a sound will be played when a notification is displayed on the device.

Note : On Android authorizationStatus will return authorized if the user has not disabled notifications for the app via the operating systems settings.

Add runtime permissions for push notification#

From Android 13, To receive notification message, we need below permissions:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />