Integrate Firebase Messaging with Flutter

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-messaging:20.1.0'
}
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
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"));
}
}
<application
android:name=".Application"

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.

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();
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,
),
],
),
),
);
}
flutter run
@override
void initState() {
// TODO: implement initState
super.initState();
_firebaseMessaging.configure(
onMessage: (message) async{
setState(() {
messageTitle = message["notification"]["title"];
notificationAlert = "New Notification Alert";
});
},
onResume: (message) async{
setState(() {
messageTitle = message["data"]["title"];
notificationAlert = "Application opened from Notification";
});
},
);
}

Step 8: Create a Message from the Firebase Cloud Messaging Console

First, we need to go back to the Cloud Messaging console in the Firebase site as shown in the image below:

Flutter Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store