DEV Community

Cover image for Flutter Push Notification on document create Firestore
Sanskar Tiwari
Sanskar Tiwari

Posted on • Originally published at flutternerd.com

Flutter Push Notification on document create Firestore

Learn how to send a push notification to Android, IOS, and Flutter Web on new document creation on Firestore.

đź“• Things covered in this tutorial:

  • Connecting Flutter App to Firebase
  • Sending test message from Firebase Cloud Messaging to Android device.
  • Adding Multidex support
  • Creating cloud function to listen for new document create and push notification automatically to a single device by the token.

Make sure you have flutter installed if not visit flutter.dev

So let’s get started coding,

Step 1: Create a flutter project, I am going to do it with Android studio you can user terminal/cmd or VS code there will be no difference.

to create project in android studio click +Start a new flutter project > select flutter application > provide project name and click next.

Step 2: We will start by getting rid of all the comments in the main.dart and getting rid of MyHomePage() stateful widget

this helps in getting the code more clean to work with.

Step 3: Create a folder/package inside the lib

we will create all the screens in this folder so I am going to name this views. then create home.dart.

just add a stateful widget called Home can call it from MyApp.

Step 4: Create a new Firebase Project

visit firebase.com and click “Get Started” sign in with google account

click on Go to console, + Add project
Enter project name and continue.
you can add google analytics but it’s not required.
once the project is created.

Step 5: Writing cloud function code we can write it in Javascript and Typescript, don’t worry if you don’t have experience with these

we will use javascript.

Install Node.js for your operating system ( i downloaded “Recommended for Most Users”)
Step 6: Add firebase to your Android, IOS or Web app

Android

1.Select the Android Icon on Firebase Console.
2.Submit package name which you can find from app_folder/android/app/src/main/AndroidManifest.xml line:2
You can provide nickname not mandatory
3.Add SHA-1 by generating SHA-1 key and submit
Download the google-services.json file and add it to app_folder/android/app/
then add what’s missing to Project-level build.gradle

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.3'
  }
}

allprojects {
  ...
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    ...
  }
}
 then to App-level build.gradle
apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'

dependencies {
  // add the Firebase SDK for Google Analytics
  implementation 'com.google.firebase:firebase-analytics:17.5.0'
  // add SDKs for any other desired Firebase products
  // https://firebase.google.com/docs/android/setup#available-libraries
}

Enter fullscreen mode Exit fullscreen mode

click next and i usually click “skip this step” but you can run the app and confirm the connection.

Step 7: Add cloud firestore package & firebase_messaging from pub.dev

Error you may face
Multi Index : If you find this anywhere in the error then Modify your build.gradle

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"

         defaultConfig {
             minSdkVersion 14 //lower than 14 doesn't support multidex
             targetSdkVersion 22

             // Enabling multidex support.
             multiDexEnabled true
         }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
}
Enter fullscreen mode Exit fullscreen mode

Step 8: Setting up Firestore

Open firebase and select Firestore and click “Create database”
Select test mode so that we do not need to add authentication to access the database and click “Next”.
Click selecting firestore location “Done”
Step 9: Adding internet permission

Add this code snippet to AndroidManifest.xml (app_folder/android/app/src/main/AndroidManifest.xml) within the MainActivity

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

open app_folder/android/app/src/main/AndroidManifest.xml and add


Step 10: Add firebase messaging dependency to Android

at /android/app/build.gradle, latest version can be found here

com.google.firebase:firebase-messaging:20.2.4
Step 11: Setting up Firebase Messaging to Your Flutter App:

Add Firebase Messaging variable and initialise.
create a initstate() and then create a function getToken();
Adding getToken() to the initi state
We also added requestNotificationPermissions for IOS

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  String token = '';
  final FirebaseMessaging firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    getToken();

    firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(
        alert: true,
        badge: true,
        provisional: true,
        sound: true
      )
    );

    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);
      },
    );

    super.initState();
  }

  void getToken() async {
    token = await firebaseMessaging.getToken();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(child: Text("Token : $token")),
      floatingActionButton: FloatingActionButton(onPressed: (){
        print(token);
      },
        child: Icon(Icons.print),
      ),
    );
  }

}

Enter fullscreen mode Exit fullscreen mode

Step 12: Run the App & Get Device token from console when clicking on floating action button.

Step 13: Let’s test if it is working

Visit Firebase “Grow Section” > “Cloud Messaging”

Click on “Send your first message”
Enter title
Enter notification text
click on “Send test message”
submit FCM token
Now make sure the app is in background app will not receive notification if it is in foreground
click on “Test”
you will receive notification on your device.

Step 14: Time to write Cloud Function

1.Visit firebase in the Developer Section click on “Functions”.
2.Click on Get Started
Install firebase tools by running the command as shown in the new folder after opening it in VS code.
Make sure you are logged in to firebase through the terminal

run “firebase login”
then “firebase init”

Now select Functions by clicking the [Space] key then enter
select Use an existing project (remember the project we created before)

Select Javascript for Language

then to use EsLint just click enter

Now the project is setting up once done, Open the index.js file and remove everything and paste as i pasted below

const functions = require("firebase-functions");

admin.initializeApp(functions.config().firebase);

const fcm = admin.messaging();

exports.senddevices = functions.firestore
  .document("notification/{id}")
  .onCreate((snapshot) => {
    const name = snapshot.get("name");
    const subject = snapshot.get("subject");
    const token = snapshot.get("token");

    const payload = {
      notification: {
        title: "from " + name,
        body: "subject " + subject,
        sound: "default",
      },
    };

    return fcm.sendToDevice(token, payload);
  }); 

Enter fullscreen mode Exit fullscreen mode

Step 15: Let’s deploy this now

run “firebase deploy” and visit the Dashboard section in Function you will be able to see the added function

Step 16: Now open Firestore in firebase

Add a new collection named “notification” as we mentioned in the cloud function and add a document with three values as we require in the cloud function.

click save now if your app is in background you should see the notification

So finally we have successfully added Flutter Push Notification on document create Firestore 🎉.

If you have any questions? any error/problem you are facing feel free to comment them down I will get back to you as soon as possible.

🎓 More tutorials you may like

1.Build a Fully Functioning Flutter Chat App with Firebase
In this one you learn to build a fully functioning chat app with one-2-one real time chat search user like Insta DM.

👉 https://flutternerd.com/build-a-fully-functioning-flutter-chat-app-with-firebase-part-1-4/

2.Build a Wallpaper App with Flutter
In this You will learn how to build a Wallpaper app with Flutter this is a great project to add to portfolio

https://flutternerd.com/build-a-wallpaper-app-with-flutter/

3.Build a Flutter News App with NewsApi Org
In this project we will use NewsAPI.org and build a news app with it

https://flutternerd.com/news-app-with-newsapi-org-flutter/

Top comments (0)