Firebase Cloud Messaging

 

what are push notifications?

Push Notifications are a sort of pop-up messaging medium that alerts app users to what's going on in the app. They are also an important way to amplify user engagement in your app.

For example, say a user forgets about the app once they have installed it. Then you can use push notifications as a mechanism to regain and retain their interest. Push notifications also help drive traffic to your app.

Firebase Cloud Messaging is a service offered by Firebase which lets you send these notifications to your users. You can set up various configurations to send different notifications to different audiences based on time and routine.

Because of all these benefits, we are going to use it to send notifications to our Flutter app.

Step 1: Create a Flutter Project

First, we are going to create a flutter project. For that, we must have the Flutter SDK installed in our system. You can find simple steps for flutter installation in the official documentation.

After you've successfully installed Flutter, you can simply run the following command in your desired directory to set up a complete Flutter project:

flutter create pushNotification

After you've set up the project, navigate inside the project directory. Execute the following command in the terminal to run the project in either an available emulator or an actual device:

flutter run

After a successful build, you will get the following result in the emulator screen:

Step 2: Integrate Firebase Configuration with Flutter

In this step, we are going to integrate Firebase services with our Flutter project. But first, we need to create a Firebase project. The setup guidelines are also provided in the official firebase documentation for Flutter.

To create a Firebase project, we need to log in to Firebase and navigate to the console. There we can simply click on 'Add a project' to get our project started.

Then a window will appear asking to input the project's name. Here, I've kept the project name as FlutterPushNotification as shown in the screenshot below:

We can continue to the next step when the project has been created. After the project has been set up, we will get a project console as shown in the screenshot below:

Here, we are going to set up Firebase for the Android platform. So we need to click on the Android icon displayed in the above screenshot. This will lead us to the interface to register Firebase with our Flutter app project.

Step 3: Register Firebase to Your Android App

As the registration process is platform-specific, we are going to register our app for the Android platform. After clicking on the Android icon, we will be directed to an interface asking for the Android package name.

In order to add the package name of our Flutter project, we need to locate it first. The package name will be available in the ./android/app/build.gradle file of your Flutter project. You will see something like this:

com.example.pushNotification

We just need to copy it and paste it to the Android package name input field as shown in the screenshot below:

After that, we can simply click on the 'Register app' button. This will lead us to the interface where we can get the google-services.json file which will link our Flutter app to Firebase Google services.

We need to download the file and move it to the ./android/app directory of our Flutter project. The instructions are also shown in the screenshot below:

Step 4: Add Firebase Configurations to Native Files in your Flutter Project

Now in order to enable Firebase services in our Android app, we need to add the google-services plugin to our Gradle files.

First in our root-level (project-level) Gradle file (android/build.gradle), we need to add rules to include the Google Services Gradle plugin. We need to check if the following configurations are available or not:

buildscript {
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
  }
  dependencies {
    ...
    // Add this line
    classpath 'com.google.gms:google-services:4.3.4'
  }
}

allprojects {
  ...
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    ...
  }
}

If not, we need to add the configurations as shown in the code snippet above.

Now in our module (app-level) Gradle file (android/app/build.gradle), we need to apply the Google Services Gradle plugin.

For that, we need to add the piece of code highlighted in the following code snippet to the ./android/app/build.gradle file of our project:

// Add the following line:
**apply plugin: 'com.google.gms.google-services'**  // Google Services plugin

android {
  // ...
}

Now, we need to run the following command so that some automatic configurations can be made:

flutter packages get

With that we have successfully integrated Firebase configurations with our Flutter project.

Step 5: Integrate Firebase Messaging with Flutter

First, we need to add the firebase-messaging dependency to the ./android/app/build.gardle file. In the file, we need to add the following dependencies:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-messaging:20.1.0'
}

Next, we need to add an action and a category as an intent-filter within the activity tag in the ./android/app/src/main/AndroidManifest.xml file:

<intent-filter>
    <action android:name="FLUTTER_NOTIFICATION_CLICK" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Now, we need to create a Java file called Application.java in the path /android/app/src/main/java/<app-organization-path>.

Then, we need to add the code from the following code snippet inside it:

package io.flutter.plugins.pushNotification;

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;

public class Application extends FlutterApplication implements PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    @Override
    public void registerWith(PluginRegistry registry) {
        FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
    }
}

Now, we need to assign this Application activity to the application tag of the AndroidManifest.xml file as shown in the code snippet below:

<application
        android:name=".Application"

This completes our setup of the Firebase messaging plugin in the native Android code. Now, we'll move on to the Flutter project.

Step 6: Install the Firebase Messaging Package

Here, we are going to use the [firebase_messaging] package, which you can find here. For that, we need to add the plugin to the dependency option of the pubspec.yaml file.

We need to add the following line of code to the dependencies option:

firebase_messaging: ^7.0.3

Step 7: Implement a Simple UI Screen

Now, inside the MyHomePage stateful widget class of the main.dart file, we need to initialize the FirebaseMessaging instance and some constants as shown in the code snippet below:

String messageTitle = "Empty";
String notificationAlert = "alert";

FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

The messageTitle variable will receive the notification message title and notificationAlert will be assigned the action that's been completed once the notification comes up.

Now, we need to apply these variables to the build function inside the Scaffold widget body as shown in the code snippet below:

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              notificationAlert,
            ),
            Text(
              messageTitle,
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
    );
  }

Comments

Popular posts from this blog

Flutter: Exploring more widgets

Flutter: Everything is a widget

Food Delivery App 5 - Firebase Storage for Profile Picture