So a project i’ve been working on recently needed a module where i had to receive user notifications in the background and also refresh user’s info as soon as the notification was delivered to a user .
Now, this could’ve been done using the cloud function we were using to send the notification. but we needed to refresh the data only when the user received notification.
so LESGOOOOOOOO!
the plugins we’ll need:
flutter_local_notifications:
cloud_store:
firebase_messaging:
make sure you’ve set these up before proceeding
run the app once and find the **GeneratedPluginRegistrant.java **file in android/app/src/main/java/io/flutter/plugins. we’ll need these to identify the import names later.
now head over to the folder containing **MainActivity.kt **and here we’ll create a registrant class.
CloudFirestorePluginRegistrant.kt
package <com.your.application>
import android.util.Log
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin
class CloudFirestorePluginRegistrant {
companion object {
fun registerWith(registry: PluginRegistry){
Log.d("CloudFirestore", "registerWith");
if(alreadyRegisteredWith(registry)) {
Log.d("Already Registered","");
return
}
try {
CloudFirestorePlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin"))
} catch (e: Exception) {
Log.d("CloudFirestore", e.toString());}
Log.d("Plugin Registered","");
}
private fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
val key = CloudFirestorePluginRegistrant::class.java.canonicalName
if (registry.hasPlugin(key)) {
return true
}
registry.registrarFor(key)
return false
}
}
}
and now lets register this class in our **Application.kt **in the same folder
package <com.your.application>
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import com.your.application.CloudFirestorePluginRegistrant
class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
}
override fun registerWith(registry: PluginRegistry?) {
if (registry != null) {
CloudFirestorePluginRegistrant.registerWith(registry)
}}
}
and thats about it.
Note: remember to omit “notification” key from our payload to trigger onBackgroundMessage callback.
now we can simply call this code in our firebase messaging onBackgroundMessage callback:
onBackgroundMessage: _onMyBackGroundMessage;
_onMybackGroundMessage(Map<String,dynamic> message){
firestore.instance.collection(message['data'['userName'])
.document(notfication).set({name:['data']['userName]});
}
and now we can make cloud firestore queries even if the app is in background.
Top comments (1)
if you are interested in Flutter, then read this article - dev.to/pablonax/free-flutter-templ...