Successfully reported this slideshow.
Your SlideShare is downloading. ×

Push Notifications: How to add them to a Flutter App

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad

Check these out next

1 of 47 Ad

Push Notifications: How to add them to a Flutter App

Download to read offline

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

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

Advertisement
Advertisement

More Related Content

Recently uploaded (20)

Advertisement

Push Notifications: How to add them to a Flutter App

  1. 1. Push Notifications: How to add them to a Flutter App https://fibonalabs.com/
  2. 2. 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 notifications 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 to your app. The benefits of adding push notifications using Flutter are:
  3. 3. 1. Increases user retention i.e. a greater number of users download the app 2. Increases user engagement in the app 3. Significant increase in the conversion rate 4. Keeps track of user metrics 5. Improved user experience 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
  4. 4. STEP 1: Set up and create a new Firebase project ● Log in to your Google account and access the 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.
  5. 5. 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 the Android icon, shown on the Project Overview Screen and it will direct you to a form. ● Fill in the following details: Android package name (get it from the following path project directory → android → app → src → main → AndroidManifest.xml). Next, enter a nickname for your app (optional).
  6. 6. Enter SHA-1 hash (click on the help icon to know where to get the SHA-1 hash value)
  7. 7. ● Click “Register app” and your app will be registered. ● Next, download the 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 }
  8. 8. dependencies { ... // Add this line classpath 'com.google.gms:google-services:4.3.4' } } allprojects { ... repositories {
  9. 9. 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 the Android app will be completed.
  10. 10. 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 the Flutter app. ● firebase_messaging: Helps in receiving notifications in the Flutter app. ● overlay_support: Helps in building overlay UI.
  11. 11. To add these packages to your project: ● Get their latest version from the 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:
  12. 12. 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 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.
  13. 13. ● 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) { // ... }
  14. 14. ● 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;
  15. 15. ● Now, 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
  16. 16. { // Parse the message received PushNotification notification = PushNotification( title: message.notification?.title, body: message.notification?.body, ); setState(() { _notificationInfo = notification; _totalNotifications++;
  17. 17. }); } 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:
  18. 18. Step 5: Sending Push Notification in your Flutter app If you got to step 3, you will find we have used an overlays-support plugin. This comes into action now. Here we will show how firebase cloud messaging has made it easy for you to receive the notifications while: 1. the app is in use 2. the app is in minimized state 3. App is in a closed state
  19. 19. When App is in use
  20. 20. ● 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( // ... ),
  21. 21. } } ● Now to display the Push Notification inside your app use the function showSimpleNotification(). void registerNotification() async { //… if (settings.authorizationStatus == AuthorizationStatus.authorized) {
  22. 22. { // ... if (_notificationInfo != null) { // For displaying the notification as an overlay showSimpleNotification( Text(_notificationInfo!.title!), leading: NotificationBadge(totalNotifications: _totalNotifications), subtitle: Text(_notificationInfo!.body!),
  23. 23. duration: Duration(seconds: 2), ); } }); } else { print('User declined or has not accepted permission'); } }
  24. 24. ● 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(
  25. 25. appBar: AppBar( title: Text('Notify'), brightness: Brightness.dark, ), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ //...
  26. 26. _notificationInfo != null ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'TITLE: ${_notificationInfo!.title}', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16.0,
  27. 27. ), SizedBox(height: 8.0), Text( 'BODY: ${_notificationInfo!.body}', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16.0, ), ),
  28. 28. ) : Container(), ], ), ); } } Shown above is a column with the two text widgets i.e., notification title and body.
  29. 29. When App is in Minimized State
  30. 30. ● 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}"); }
  31. 31. Now, call the method onBackgroundMessage(). void registerNotification() async { await Firebase.initializeApp(); _messaging = FirebaseMessaging.instance; // Add the following line FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackground Handler); // ... } ● If your app is running in the background and you tapped on the received notification, then this action needs to be handled using the initState()
  32. 32. @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(() {
  33. 33. _totalNotifications++; }); }); super.initState(); }
  34. 34. When App is in Closed State
  35. 35. As we know, Push Notifications can also be sent while the app is in the 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() in this method. // For handling notification when the app is in terminated state checkForInitialMessage() async { await Firebase.initializeApp(); RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
  36. 36. if (initialMessage != null) { PushNotification notification = PushNotification( title: initialMessage.notification?.title, body: initialMessage.notification?.body, ); setState(() { _notificationInfo = notification; _totalNotifications++; });
  37. 37. } Next, call this method, for iniState method(). @override void initState() { // ... // Call here checkForInitialMessage(); // ...
  38. 38. } 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
  39. 39. ● 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">
  40. 40. android:name=".MainActivity" <!-- ... --> <!-- Add this tag --> <intent-filter> <action android:name="FLUTTER_NOTIFICATION_CLICK" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
  41. 41. <!-- ... --> </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.
  42. 42. THANK YOU

×