The Flutterfire plugin that adds the Cloud Messaging capabilities is called firebase_messaging.
Add it to your app from the terminal typing:
flutter pub add firebase_messaging
Then, at the top of the main.dart file, import the plugin: this is from the firebase_messaging package, and the file we want to import is firebase_messaging.dart.
import 'package:firebase_messaging/firebase_messaging.dart';
Next, in the main method, retrieve the messaging instance: declare a final, called messaging, that takes the FirebaseMessaging instance.
final messaging = FirebaseMessaging.instance;
From now on, you can deal with the notifications and data that you receive. There are two events we will listen two, depending on the state of the app: one is onBackgroundMessage, that’s called when the app is not visible to the user (so when your app is in the background or terminated): so type FirebaseMessaging.onBackgroundMessage, and as a parameter pass a function that we will create shortly, and call it handle_message
FirebaseMessaging.onBackgroundMessage(_handleMessage);
Let’s create the _handleMessage method: this is a Future, that takes a RemoteMessage object, and is asynchronous. Here we just want to print the content of the notification in the debug console: so, let’s print “background message” and in the message, let’s get the notification, with a bang operator, and its title. Let’s repeat with the notification body.
Future<void> _handleMessage(RemoteMessage message) async {
print('background message title ${message.notification!.title}');
print('background message body ${message.notification!.body}');
print('background data ${message.data.length}');
}
As you can see Firebase Cloud Messaging provides a Remote message: this contains a notification object, and the notification has a title and a body. A remote message also contains a data object, which is a map of key value pairs. Just to check if it exists, let’s also print the length of the data object contained in the message.
So, this method currently deals with messages received in the background. Let’s also deal with notifications received when the app is in the foreground: in this case we’ll be using the onmessage property, and over it, call the listen method. This also takes a function that receives a Remote message.
This time, let’s just print: Message received in the foreground. If the notification in the message is not null, let’s also print the notification body in the debug console:
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Message received in the foreground!');
if (message.notification != null) {
print(
'Message notification: ${message.notification?.body}');
}
});
Ok, before testing the notifications on this app, if you are using iOS you need to set a few permissions first.