Flutter Firebase Cloud Messaging Examples
Flutter Firebase Cloud Messaging
Introduction
Firebase Cloud Messaging (FCM) is a free cloud messaging service provided by Google that allows you to send notifications and messages to devices.
In this tutorial, we will learn how to integrate Firebase Cloud Messaging into a Flutter application. We will cover the installation process, setting up Firebase project, and implementing various examples to send and receive push notifications.
Installation
To get started with Flutter Firebase Cloud Messaging, you need to follow these steps:
Start by creating a new Flutter project using the following command in your terminal:
flutter create flutter_fcm_example
Open the
pubspec.yaml
file in your project's root directory and add thefirebase_messaging
dependency:dependencies:
flutter:
sdk: flutter
firebase_messaging: ^10.0.0Save the file and run the following command to fetch the dependency:
flutter pub get
Now, you need to set up a Firebase project. Go to the Firebase Console and create a new project.
Once the project is created, click on "Add app" and select the Flutter platform.
Follow the on-screen instructions to download the
google-services.json
file and place it inside theandroid/app
directory of your Flutter project.To complete the setup, open the
android/build.gradle
file and add the following line of code inside thedependencies
block:classpath 'com.google.gms:google-services:4.3.10'
Save the file and open the
android/app/build.gradle
file. Add the following line at the bottom of the file:apply plugin: 'com.google.gms.google-services'
Save the file and run the following command to sync the project with the changes:
flutter pub get
Congratulations! You have successfully installed Firebase Cloud Messaging in your Flutter project.
Example 1: Sending a Notification
In this example, we will learn how to send a notification to a specific device using Firebase Cloud Messaging.
Import the necessary packages in your
main.dart
file:import 'package:firebase_messaging/firebase_messaging.dart';
Initialize the Firebase Cloud Messaging instance in the
main
function:void main() {
// Initialize Firebase Cloud Messaging
FirebaseMessaging.instance.initializeApp();
runApp(MyApp());
}Request permission to receive notifications in your
MyApp
widget:class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
FirebaseMessaging.instance.requestPermission();
// Rest of the code
}
}To receive notifications, add the following code inside your
MyApp
widget'sbuild
method:FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
if (message != null) {
// Handle the initial notification
}
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Handle the received notification
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// Handle the notification opened from the background or terminated state
});To send a notification, you can use the Firebase Cloud Messaging API or the Firebase Console. Here's an example of sending a notification using the API:
Future<void> sendNotification() async {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=YOUR_SERVER_KEY',
},
body: jsonEncode(<String, dynamic>{
'notification': <String, dynamic>{
'body': 'This is a test notification',
'title': 'Test Notification',
},
'to': 'DEVICE_TOKEN',
}),
);
}
Replace YOUR_SERVER_KEY
with your Firebase Cloud Messaging server key and DEVICE_TOKEN
with the device token of the device you want to send the notification to.
Example 2: Handling Data Messages
In addition to sending notifications, Firebase Cloud Messaging also supports sending data messages. Data messages allow you to send custom data payloads to your Flutter app.
To handle data messages, add the following code inside your
MyApp
widget'sbuild
method:FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Handle the received data message
final Map<String, dynamic>? data = message.data;
// Use the received data
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// Handle the data message opened from the background or terminated state
final Map<String, dynamic>? data = message.data;
// Use the received data
});To send a data message, update the
sendNotification
method from the previous example:Future<void> sendDataMessage() async {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=YOUR_SERVER_KEY',
},
body: jsonEncode(<String, dynamic>{
'data': <String, dynamic>{
'key1': 'value1',
'key2': 'value2',
},
'to': 'DEVICE_TOKEN',
}),
);
}
Replace YOUR_SERVER_KEY
with your Firebase Cloud Messaging server key and DEVICE_TOKEN
with the device token of the device you want to send the data message to.
Example 3: Handling Notification Clicks
In this example, we will learn how to handle notification clicks in a Flutter app.
Add the following code inside your
MyApp
widget'sbuild
method:FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// Handle the notification clicked when the app is in the background or terminated state
// Use the received data
});To handle the notification click when the app is in the foreground, add the following code inside your
MyApp
widget'sbuild
method:FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Handle the received notification and data
final Map<String, dynamic>? data = message.data;
// Use the received data
});
That's it! You have learned how to handle notification clicks in your Flutter app.
Example 4: Customizing Notification Appearance
Firebase Cloud Messaging allows you to customize the appearance of the notifications you send.
To customize the notification appearance, you need to create a custom Flutter notification widget and set it as the value of the notification
field when sending the notification.
Here's an example of creating a custom notification widget:
class CustomNotification extends StatelessWidget {
final String title;
final String body;
const CustomNotification({required this.title, required this.body});
Widget build(BuildContext context) {
return Container(
child: ListTile(
title: Text(title),
subtitle: Text(body),
),
);
}
}
To send a notification with a custom appearance, update the sendNotification
method from the first example:
Future<void> sendCustomNotification() async {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=YOUR_SERVER_KEY',
},
body: jsonEncode(<String, dynamic>{
'notification': <String, dynamic>{
'body': 'This is a custom notification',
'title': 'Custom Notification',
'android': {
'notification': {
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'priority': 'high',
'style': 'inbox',
'channel_id': 'default_channel',
'small_icon': 'ic_launcher',
'content_available': true,
'default_sound': true,
'default_vibrate_timings': true,
'default_light_settings': true,
'visibility': 'public',
'notification_priority': 'PRIORITY_MAX',
'sound': 'default',
'vibration': 'default',
'color': '#FF0000',
'ticker': 'ticker_text',
'local_only': false,
'show_in_foreground': true,
'category': 'event',
'tag': 'tag',
'group': 'group',
'icon': 'ic_launcher',
'sound_uri': 'default',
'image': 'https://example.com/image.png',
'lights': {
'color': '#FF0000',
'onMs': 500,
'offMs': 500,
},
},
},
},
'to': 'DEVICE_TOKEN',
}),
);
}
Replace YOUR_SERVER_KEY
with your Firebase Cloud Messaging server key and DEVICE_TOKEN
with the device token of the device you want to send the notification to.
Example 5: Sending a Topic-based Notification
Firebase Cloud Messaging allows you to send notifications to devices subscribed to a specific topic.
To send a topic-based notification, use the sendToTopic
method instead of the send
method.
Here's an example of sending a topic-based notification:
Future<void> sendTopicNotification() async {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=YOUR_SERVER_KEY',
},
body: jsonEncode(<String, dynamic>{
'notification': <String, dynamic>{
'body': 'This is a topic-based notification',
'title': 'Topic-based Notification',
},
'condition': "'topic' in topics",
}),
);
}
Replace YOUR_SERVER_KEY
with your Firebase Cloud Messaging server key and 'topic'
with the topic you want to send the notification to.
Example 6: Handling Token Changes
Firebase Cloud Messaging provides a device token that identifies the device for receiving notifications. This token can change over time, so it's important to handle token changes in your Flutter app.
- Add the following code inside your
MyApp
widget'sbuild
method:
FirebaseMessaging.instance.onTokenRefresh.listen((String token) {
// Handle the token refresh
});
- To retrieve the current token, you can use the following code:
String? token = await FirebaseMessaging.instance.getToken();
Example 7: Customizing Notification Sounds
Firebase Cloud Messaging allows you to customize the sound played when a notification is received.
To customize the notification sound, you need to set the sound
field of the notification
object when sending the notification.
Here's an example of sending a notification with a custom sound:
Future<void> sendCustomSoundNotification() async {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=YOUR_SERVER_KEY',
},
body: jsonEncode(<String, dynamic>{
'notification': <String, dynamic>{
'body': 'This is a custom sound notification',
'title': 'Custom Sound Notification',
'sound': 'custom_sound',
},
'to': 'DEVICE_TOKEN',
}),
);
}
Replace YOUR_SERVER_KEY
with your Firebase Cloud Messaging server key, DEVICE_TOKEN
with the device token of the device you want to send the notification to, and 'custom_sound'
with the name of the custom sound file.
Example 8: Handling Notification Actions
Firebase Cloud Messaging allows you to add actions to your notifications. These actions can be triggered when the user interacts with the notification.
To handle notification actions, add the following code inside your MyApp
widget's build
method:
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Handle the received notification and data
final Map<String, dynamic>? data = message.data;
if (message.notification != null) {
final String? action = message.notification?.android?.clickAction;
if (action != null) {
// Handle the notification action
}
}
});
Example 9: Sending a Notification with Big Picture
Firebase Cloud Messaging allows you to send notifications with big pictures. Big pictures can be used to provide more visual context to the notification.
To send a notification with a big picture, update the sendNotification
method from the first example:
Future<void> sendBigPictureNotification() async {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=YOUR_SERVER_KEY',
},
body: jsonEncode(<String, dynamic>{
'notification': <String, dynamic>{
'body': 'This is a big picture notification',
'title': 'Big Picture Notification',
'android': {
'notification': {
'style': 'bigpicture',
'picture': 'https://example.com/picture.png',
'big_picture': 'https://example.com/big_picture.png',
},
},
},
'to': 'DEVICE_TOKEN',
}),
);
}
Replace YOUR_SERVER_KEY
with your Firebase Cloud Messaging server key and DEVICE_TOKEN
with the device token of the device you want to send the notification to.
Example 10: Sending a Notification with a Data URI
Firebase Cloud Messaging allows you to send notifications with a data URI. A data URI can be used to open a specific content in the app when the notification is clicked.
To send a notification with a data URI, update the sendNotification
method from the first example:
Future<void> sendDataUriNotification() async {
await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=YOUR_SERVER_KEY',
},
body: jsonEncode(<String, dynamic>{
'notification': <String, dynamic>{
'body': 'This is a data URI notification',
'title': 'Data URI Notification',
'android': {
'notification': {
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'data': {
'uri': 'https://example.com/content',
},
},
},
},
'to': 'DEVICE_TOKEN',
}),
);
}
Replace YOUR_SERVER_KEY
with your Firebase Cloud Messaging server key and DEVICE_TOKEN
with the device token of the device you want to send the notification to.
Conclusion
In this tutorial, we have learned how to integrate Firebase Cloud Messaging into a Flutter application. We covered the installation process, setting up Firebase project, and implementing various examples to send and receive push notifications.
Firebase Cloud Messaging is a powerful tool for sending notifications and messages to devices. With the knowledge gained from this tutorial, you can now leverage the capabilities of Firebase Cloud Messaging in your Flutter apps.