Push notifications are a message that pops up on a mobile device. App publishers can send them at any time, users don’t have to be in the app or using their devices to receive them. They can do a lot of things. for example, they can show the latest sports scores, get a user to take any action, such as downloading a coupon or let a user know about an event, such as a flash sale.
Read about the variety of Flutter App Development Services offered by Mobikul.
Push notifications look like SMS text messages and mobile alerts, but they only reach users who have installed your app. Each mobile platform has support for push notifications — iOS, Android, and many other OS have their own services.
To implement notification, add firebase_messaging
as a dependency in your pubspec.yaml file.
Push Notifications Integration for Android
1) Using the Firebase Console add an Android app to your project: Follow the assistant, download the generated google-services.json
file and place it inside android/app
.
2) Add the classpath to the [project]/android/build.gradle
file.
1 2 3 4 5 6 |
dependencies { // Example existing classpath classpath 'com.android.tools.build:gradle:3.5.3' // Add the google services classpath classpath 'com.google.gms:google-services:4.3.2' } |
3) Add the apply plugin to the [project]/android/app/build.gradle
file.
1 2 |
// ADD THIS AT THE BOTTOM apply plugin: 'com.google.gms.google-services' |
Note: If this section is not completed you will get an error like this:
1 |
java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process [package name]. Make sure to call FirebaseApp.initializeApp(Context) first. |
Note: When you are debugging on Android, use a device or AVD with Google Play services. Otherwise, you will not be able to authenticate.
4) (optional, but recommended) If want to be notified in your app (via onResume
and onLaunch
, see below) when the user clicks on a notification in the system tray include the following intent-filter
within the <activity>
tag of your android/app/src/main/AndroidManifest.xml
:
1 2 3 4 |
<intent-filter> <action android:name="FLUTTER_NOTIFICATION_CLICK" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> |
Optionally handle background messages
Background message handling is intended to be performed quickly. Do not perform long running tasks as they may not be allowed to finish by the Android system. See Background Execution Limits for more.
By default background messaging is not enabled. To handle messages in the background:
1) Add the com.google.firebase:firebase-messaging
dependency in your app-level build.gradle
file that is typically located at <app-name>/android/app/build.gradle
.
1 2 3 4 |
dependencies { // ... implementation 'com.google.firebase:firebase-messaging:<latest_version>' } |
Note: you can find out what the latest version of the plugin is here (“Cloud Messaging”).
2) Define a TOP-LEVEL or STATIC function to handle background messages
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) { if (message.containsKey('data')) { // Handle data message final dynamic data = message['data']; } if (message.containsKey('notification')) { // Handle notification message final dynamic notification = message['notification']; } // Or do other work. } |
Note: the protocol of data
and notification
are in line with the fields defined by a RemoteMessage.
3) Set onBackgroundMessage
handler when calling configure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
_firebaseMessaging.configure( onMessage: (Map<String, dynamic> message) async { print("onMessage: $message"); _showItemDialog(message); }, onBackgroundMessage: myBackgroundMessageHandler, onLaunch: (Map<String, dynamic> message) async { print("onLaunch: $message"); _navigateToItemDetail(message); }, onResume: (Map<String, dynamic> message) async { print("onResume: $message"); _navigateToItemDetail(message); }, ); |
Push Notifications Integration for iOS
To integrate your plugin into the iOS part of your app, follow these steps:
- Generate the certificates required by Apple for receiving push notifications following this guide in the Firebase docs. You can skip the section titled “Create the Provisioning Profile”.
- Using the Firebase Console add an iOS app to your project: Follow the assistant, download the generated
GoogleService-Info.plist
file, openios/Runner.xcworkspace
with Xcode, and within Xcode place the file insideios/Runner
. Don’t follow the steps named “Add Firebase SDK” and “Add initialization code” in the Firebase assistant. - In Xcode, select
Runner
in the Project Navigator. In the Capabilities Tab turn onPush Notifications
andBackground Modes
, and enableBackground fetch
andRemote notifications
underBackground Modes
. - Follow the steps in the “Upload your APNs certificate” section of the Firebase docs.
- If you need to disable the method swizzling done by the FCM iOS SDK (e.g. so that you can use this plugin with other notification plugins) then add the following to your application’s
Info.plist
file.
1 2 |
<key>FirebaseAppDelegateProxyEnabled</key> <false/> |
After that, add the following lines to the (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
method in the AppDelegate.m
/AppDelegate.swift
of your iOS project.
Objective-C:
1 2 3 4 |
if (@available(iOS 10.0, *)) { [UNUserNotificationCenter currentNotificationCenter].delegate = (id<UNUserNotificationCenterDelegate>)self; } |
Swift:
1 2 3 |
if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate } |
Dart/Flutter Integration
From your Dart code, you need to import the plugin and instantiate it:
1 2 3 |
import 'package:firebase_messaging/firebase_messaging.dart'; final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); |
Next, you should probably request permissions for receiving Push Notifications. For this, call _firebaseMessaging.requestNotificationPermissions()
. This will bring up a permissions dialog for the user to confirm on iOS. It’s a no-op on Android. Last, but not least, register onMessage
, onResume
, and onLaunch
callbacks via _firebaseMessaging.configure()
to listen for incoming messages (see table below for more information).
Receiving Messages
Messages are sent to your Flutter app via the onMessage
, onLaunch
, and onResume
callbacks that you configured with the plugin during setup.
Notification messages with additional data
It is possible to include additional data in notification messages by adding them to the "data"
-field of the message.
On Android, the message contains an additional field data
containing the data. On iOS, the data is directly appended to the message and the additional data
-field is omitted.
To receive the data on both platforms:
1 2 3 4 5 |
Future<void> _handleNotification (Map<dynamic, dynamic> message, bool dialog) async { var data = message['data'] ?? message; String expectedAttribute = data['expectedAttribute']; /// [...] } |
Sending Messages
Refer to the Firebase documentation about FCM for all the details about sending messages to your app. When sending a notification message to an Android device, you need to make sure to set the click_action
property of the message to FLUTTER_NOTIFICATION_CLICK
. Otherwise, the plugin will be unable to deliver the notification to your app when the users click on it in the system tray.
For testing purposes, the simplest way to send a notification is via the Firebase Console. Make sure to include click_action: FLUTTER_NOTIFICATION_CLICK
as a “Custom data” key-value-pair (under “Advanced options”) when targeting an Android device. The Firebase Console does not support sending data messages.
Output
You will get the notification same like the native apps and also customize the notification alert design like this-
Push Notifications for Flutter using Firebase
Thank You for reading this article!!!