Building compelling applications with rich user engagement often requires real-time updates and consistent communication with your audience. Flutter Push notifications are an essential channel for such engagement, and integrating them into Flutter applications can significantly enhance your app's user experience.
Push notifications are not just about app updates or marketing ploys; they are a vital tool for developers to share critical information and instantly interact with their users. Push notifications allow immediate delivery of timely updates, enhancing connectivity between the client app, and the server.
In the world of Flutter, integrating push notifications empowers developers to send timely visual signals to the user on the client-side directly from the server. Push notifications can be of various forms – from chat notifications, user activity indicators, to transactional updates, and more. This instant messaging is especially effective in driving user re-engagement and maintaining the application's active usage.
In order to implement push notifications in a Flutter app, we often use Firebase messaging Flutter solution, also known as Flutter Firebase Messaging. Firebase Cloud Messaging (FCM) offers a reliable way to send messages to multiple devices and platforms. However, there's an alternative that comes handy when Firebase cannot be used on all platforms, and that's when Push comes into play.
The Push package is mainly used when the Firebase services are not applicable, especially for cross-platform messaging solutions outside of Android. This often happens when you use another service that does not use Firebase Cloud Messaging, like Ably and OneSignal, for delivering notification messages. In such cases, the Push package lets you handle push notifications regardless of the platform-specific services.
What Makes it Stand Out Push package stands out in terms of its support for Foreground, Background, and Terminated state notifications, revoking the use of Firebase on platforms other than Android, and more. For instance, refer to the following piece of code showcasing the Push instance in action.
1 final isGranted = await Push.instance.requestPermission(); 2
In this snippet, we input permission request for app-users to start receiving push notifications.
When talking about push notifications in a Flutter project, we encounter several libraries. Let's understand how each one stands in comparison to others.
Firebase Messaging is the de facto solution when we discuss Flutter FCM. Firebase Cloud Messaging (FCM) is a standard tool for sending notifications across platforms. But this approach includes an extra step of transporting the message through FCM and then to Apple Push Notification Service (APNs) for iOS which might lead to some latency.
Firebase Messaging also uses a deprecated Android component (JobIntentService) which keeps on running, waiting for messages even when no data messages are being delivered.
Another important point - this still is a requirement for iOS, Firebase Messaging servers need to be up and running to ensure the functioning of notifications on iOS.
Flutter_apns used to be a popular package for managing push notifications though now it's considered "dead" due to lack of maintenance. Its biggest downside is the lack of support for background notifications and adding up the Firebase messaging dependency whether or not the app utilizes Firebase on iOS. This, unfortunately, makes it less favoured in comparison to Push.
Consider this package as a potential choice, especially if you're targeting iOS platforms. The hiccup arises when you need to support Android as well. It would need the introduction of firebase_messaging, which clashes with this package, making it less of a workaround.
While UnifiedPush is a decent choice for Android where it sets up its push services, it falls short for iOS as it bypasses FCM/APNs.
Each of these packages has its own unique points and constraints. While Firebase Messaging is the most standardized approach usually adopted, Push can be a saviour in scenarios where Firebase can't be used.
Integrating Push into your Flutter application involves a few key steps. To get started, setting up your environment correctly is crucial.
The example application is the best place to start for testing push notifications swiftly. You need to begin by cloning the project and opening the push package in your preferred IDE (like Android Studio or Visual Studio Code). Here's how you'd get started:
1 // Download dependencies 2 flutter pub get 3 4 // Clone the project and open the push package ($repo_folder/push) in Android Studio or Visual Studio Code 5 git clone https://github.com/your-repo-name/push.git 6 7 // Navigate to the push package 8 cd push 9 10
You then need to set up a Firebase project, add an Android application using the applicationId (for instance, uk.orth.push.example), and download a google-services.json file that should be placed in the push/android/app directory.
Running the Flutter app goes as follows:
1 // Run the example app 2 flutter run 3
After booting, the FCM registration token from the app would serve as a key for exchanging messages from your server.
Sending messages to the device involves utilizing its FCM registration token, via the Firebase Admin SDK.
To enable push notifications functionality in your Android device, you need to integrate with Firebase. It involves setting up a Firebase project, adding the Android app to it, and modifying your Android project to include the required dependencies and configurations.
Firstly, set up your Firebase project and add your Android app to the project using the applicationId defined in the build.gradle file. Follow these steps in the Firebase console.
After setting the Firebase project, link it to your Android app by modifying the build.gradle files and including the specified plugins and dependencies. Here is a sample introduction of this required addition:
1 // Add to your app's android/app/build.gradle 2 apply plugin: 'com.google.gms.google-services' 3 4 // Add to your app's android/build.gradle 5 classpath 'com.google.gms:google-services:4.3.10' 6
Finally, add the push package in your pubspec.yaml file, followed by the installation of all the dependencies required.
1 // Add to your app's pubspec.yaml 2 dependencies: 3 push: ^1.0.5 4 5 // Download/update dependencies 6 flutter pub get 7
Implementing push notifications on iOS may need extra initial setup steps, some of which are platform-specific.
For instance, to start with, you need an active Apple Developer Program membership. Though it comes with an annual fee, it's necessary to access the resources for development and distribution.
To send push notifications, you need to create a key on your Apple Developer account's Certificates, Identifiers & Profiles page.
Now that we have our setup ready, let's explore how to use Flutter push notifications in your application effectively. This includes requesting permissions, handling notifications, handling taps on notifications, and understanding the usage within a StatefulWidget.
Permissions are profoundly crucial in making notification messages functional. The user's consent is needed to display notifications. In most cases, you should request permissions from the user when they have performed an action that requires notifications or anytime during the app lifecycle when it's meaningful.
Here's a code snippet for appropriate permission requests:
1 // Request permission to show notifications to the user 2 final isGranted = await Push.instance.requestPermission(); 3
On receiving a notification, you need to handle it appropriately based on where your application was during the notification arrival (foreground, background, or terminated). Here's an example of a handler set up to listen to incoming messages:
1 Push.instance.onMessage.listen((message) { 2 print('RemoteMessage received while app is in foreground:\n' 3 'RemoteMessage.Notification: ${message.notification} \n' 4 ' title: ${message.notification?.title.toString()}\n' 5 ' body: ${message.notification?.body.toString()}\n' 6 'RemoteMessage.Data: ${message.data}'); 7 messagesReceived.value += [message]; 8 }); 9
Notifications are much more than just visual cues. Tapping a notification can lead the users to a specific part of the app or take a specific action. Handling such cases would need:
1 Push.instance.onNotificationTap.listen((data) { 2 print('Notification was tapped:\n' 3 ' Data: ${data} \n'); 4 tappedNotificationPayloads.value += [data]; 5 }); 6
In cases when you use a StatefulWidget, you should store each stream you listen to (via .listen()) in your state. You should initialize these streams in initState, and cancel them in the dispose method to prevent memory leak.
Being able to manually test and debug your push notifications is incredibly important for ensuring that they work correctly before you ship your app. There are various tools and resources available to help you debug and test quickly.
Cross-checking the tools/ folder in the GitHub repository can be an excellent place to start.
You can test your application's push notifications by sending test messages from the Firebase console or by using the Firebase CLI to send a message directly to your device via its FCM registration token.
Send notification messages to the device using Firebase Admin SDK. The Firebase Cloud Messaging provides a testing suite where you can send dummy foreground and background messages to your app and check if they are correctly received.
1 # Test message sending via Firebase CLI 2 firebase messaging:send --project my-firebase-project --message=' 3 { 4 "notification": { 5 "title": "Test title", 6 "body": "Test body" 7 }, 8 "token": "my_fcm_registration_token" 9 } 10 ' 11
The successful execution of the above command will ensure that you can send notifications to this device from your server.
The process allows spotting possible issues and helps polish the user experience, making sure the push notifications work seamlessly and are properly formatted.
In order to properly use Push, it’s essential to understand how it works, the concepts of receiving notifications, and the conditions of your app when it receives them.
Push allows you to set up your message handlers as you need them, providing flexibility other packages might not offer.
There are three states in which your Flutter application can exist when dealing with push notifications:
Different scenarios and use-cases call for handling these states uniquely when dealing with notification messages to ensure optimal user experience.
When your app receives a notification, it has to process it and decide how to alert the user, if at all.
For notifications received in the foreground, the app should handle them straight away. However, in the case of incoming messages while the app is in the background or terminated, care must be taken to handle them appropriately. For these scenarios, you need handlers that process the received message, as well as handlers that drive user re-engagement directly from the notification tap.
1 Push.instance.onMessage.listen((message) { 2 //Handle notification here 3 }); 4 5 Push.instance.onBackgroundMessage.listen((message) { 6 //Handle background notification here 7 }); 8
When a user taps on a notification, it can open the Flutter app or bring it forward if it’s in the background. In such cases, specific actions or navigation could be necessary. Having tap handlers makes it easier to control these notifications.
Once you have the push notification functionality integrated into your Flutter application, it's crucial to be sure everything is set up correctly. This checklist will help ensure your application sends and receives push notifications successfully.
When using custom code in your MainActivity, remember that it doesn't run when the push package launches your application. Therefore, it is recommended to run your native logic not just when the UI is shown (FlutterActivity) but whenever the application launches. This can be done by moving the custom code out of your MainActivity and into a new custom Application class like a FlutterApplication.
Here's an example of what a custom Application class would look like:
1 class ExampleApplication : FlutterApplication() { 2 override fun onCreate() { 3 // Run custom native code for your Android application 4 super.onCreate() 5 } 6 } 7
If you implement your own FirebaseMessagingService, or use another package which does (e.g., firebase_messaging), this impacts how the push notifications are handled. You need to communicate all new tokens to the Push package in your FirebaseMessaging#onNewToken override method.
Here’s how:
1 override fun onNewToken(registrationToken: String) { 2 super.onNewToken(registrationToken) 3 PushPlugin.onNewToken(this, registrationToken) 4 } 5
Following the above-given checklist can help you determine whether your push notifications in your Flutter application will be successfully received or not.
The federated way of implementing services is a cutting-edge approach paving the way for better future app developments. This approach allows you to provide a custom implementation for specific platforms by creating your own package that implements the interface provided by push_platform_interface.
Thanks to the federated system, even if your package is not directly supported in Flutter's Push, it can still be used in the application with some modifications to the pubspec.yaml. This provides a lot of flexibility and room for customization, allowing developers or organizations to implement push services for different platforms that may not already have a mechanism for pushing data to devices from servers.
To create a custom implementation, you can simply create a new package, implement the PushPlatform interface declared in push_platform_interface/pubspec.yaml, and then point your application to use your custom package.
Thus, the federated approach broadens the scope of platform-specific customization, enabling increased flexibility and compatibility across diverse platforms.
Push notifications have become an integral part of today's mobile applications, playing a critical role in user engagement and the overall app experience. As Flutter app developers, understanding the nuances of push notifications and how to seamlessly integrate them can be a game-changer. With the likes of Firebase Messaging and the Push package, setting push notifications in Flutter has become simpler and more manageable. Understanding their usage, along with practical implementation, helps pave the way towards robust and user-friendly Flutter applications. This guide aimed to provide an in-depth view of these tools and processes, equipped with code snippets and explanations. Hopefully, this has empowered your knowledge of Flutter push notifications, providing ample information and resources to improve your Flutter applications.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.