Flutter Firebase Messaging Examples
Flutter Firebase Messaging Tutorial
Introduction
Firebase Messaging is a powerful tool that allows you to send notifications and messages to your Flutter app. It provides a simple and reliable way to deliver messages to both Android and iOS devices. In this tutorial, we will explore the different features of the firebase_messaging
package in Flutter and learn how to integrate it into your app.
Installation
To get started with Firebase Messaging in Flutter, you need to install the firebase_messaging
package. Open your pubspec.yaml
file and add the following dependency:
dependencies:
firebase_messaging: ^10.0.0
Then run the following command to fetch the package:
flutter pub get
Example 1: Configuring Firebase Messaging
Before we can use Firebase Messaging, we need to configure it in our Flutter app. Follow these steps to set up Firebase Messaging:
- Go to the Firebase Console and create a new project.
- Add an Android app or an iOS app to your project, following the on-screen instructions.
- Download the
google-services.json
file (for Android) orGoogleService-Info.plist
file (for iOS) and place it in the respective app folder (android/app
for Android andios/Runner
for iOS). - Open the
android/build.gradle
file and add the following code inside thedependencies
block:
classpath 'com.google.gms:google-services:4.3.10'
- Open the
android/app/build.gradle
file and add the following code at the bottom:
apply plugin: 'com.google.gms.google-services'
- Open the
ios/Podfile
file and add the following code:
pod 'Firebase/Messaging'
- Run the following commands to install the Firebase dependencies:
cd ios
pod install
cd ..
- Import the
firebase_messaging
package in your Dart file:
import 'package:firebase_messaging/firebase_messaging.dart';
Example 2: Requesting Permission for Push Notifications
Before your app can receive push notifications, you need to request permission from the user. Use the following code to request permission and handle the user's response:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void requestPermission() async {
NotificationSettings settings = await messaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
print('User granted permission: ${settings.authorizationStatus}');
}
The requestPermission
function will prompt the user to grant permission for push notifications. Once the user responds, the settings.authorizationStatus
will indicate whether the permission was granted or denied.
Example 3: Handling Incoming Messages
To handle incoming messages, you need to set up a callback function that will be called when a new message is received. Use the following code to handle incoming messages:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void setupMessaging() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Received new message: ${message.notification?.body}');
});
}
When a new message is received, the callback function will print the body of the notification.
Example 4: Handling Notification Taps
You can also handle notification taps to perform custom actions when a user taps on a notification. Add the following code to handle notification taps:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void setupMessaging() {
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Tapped on notification: ${message.notification?.body}');
});
}
When the user taps on a notification, the callback function will print the body of the notification.
Example 5: Retrieving the Device Token
The device token is a unique identifier for each device, which is required to send push notifications. Use the following code to retrieve the device token:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void getDeviceToken() async {
String? token = await messaging.getToken();
print('Device token: $token');
}
The getDeviceToken
function will print the device token, which can be used to send push notifications to the device.
Example 6: Handling Background Messages
Firebase Messaging allows you to handle messages even when your app is in the background or terminated. Add the following code to handle background messages:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void setupMessaging() {
FirebaseMessaging.onBackgroundMessage((RemoteMessage message) {
print('Received background message: ${message.notification?.body}');
// Handle the message here
// ...
return Future.value(true);
});
}
When a background message is received, the callback function will print the body of the notification.
Example 7: Sending Data Messages
In addition to notification messages, you can also send data messages to your app. Data messages are handled by your app and can be used to trigger specific actions. Use the following code to send a data message:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void sendDataMessage() async {
await messaging.send(
data: {
'title': 'Hello',
'body': 'This is a data message',
},
topic: 'your_topic',
);
print('Data message sent');
}
The sendDataMessage
function will send a data message with the specified title and body to the specified topic. The output will indicate that the message was sent.
Example 8: Handling Data Messages
To handle data messages in your app, you can set up a callback function that will be called when a data message is received. Add the following code to handle data messages:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void setupMessaging() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (message.data.isNotEmpty) {
print('Received data message: ${message.data}');
}
});
}
When a data message is received, the callback function will print the data payload of the message.
Example 9: Sending Topic Messages
Firebase Messaging allows you to send messages to specific topics. Use the following code to send a message to a topic:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void sendTopicMessage() async {
await messaging.subscribeToTopic('your_topic');
print('Subscribed to topic');
}
The sendTopicMessage
function will subscribe the device to the specified topic. The output will indicate that the device has been subscribed.
Example 10: Unsubscribing from a Topic
If you no longer want to receive messages from a specific topic, you can unsubscribe from it. Use the following code to unsubscribe from a topic:
FirebaseMessaging messaging = FirebaseMessaging.instance;
void unsubscribeFromTopic() async {
await messaging.unsubscribeFromTopic('your_topic');
print('Unsubscribed from topic');
}
The unsubscribeFromTopic
function will unsubscribe the device from the specified topic. The output will indicate that the device has been unsubscribed.
Conclusion
In this tutorial, we explored the firebase_messaging
package in Flutter and learned how to integrate Firebase Messaging into our app. We covered various examples, including configuring Firebase Messaging, requesting permission, handling incoming messages, handling notification taps, retrieving the device token, handling background messages, sending data messages, handling data messages, sending topic messages, and unsubscribing from topics. By following these examples, you can easily add push notification functionality to your Flutter app using Firebase Messaging.