Most of the app come with a simple but super useful feature: Push Notification. By using this feature, App owner can easily remind their audience to do something. This is one of the benefit of developing App instead of Web. So in this part of the tutorial series, I will show you how to integrate Firebase Cloud Messaging (FCM) to send push notifications in your Flutter app.
After that, you can use this essential feature to keeps users engaged by delivering timely updates, reminders, promotions, or personalized messages. Even when they are not actively using the app, you can still keep “Reminding” them to come back.
What You Will Learn:
- How to set up FCM in your Flutter project.
- How to send notifications via Firebase Console.
- How to handle notification clicks and data payloads in your app.
Let’s begin our journey.
Setting Up Firebase Cloud Messaging (FCM)
The first step you need to do before integrating FCM into your Flutter app is to set it up in the Firebase Console. How to do it?
Configure Firebase Project for FCM
Go to the Firebase Console. Then select your project or create a new one. In the left sidebar, navigate to Messaging under the “Run” section.
Enable Firebase Cloud Messaging by following the setup steps provided.
For example, if you want to enable it to your Android Project, follow below steps:
Add FCM SDK to Your Flutter Project
Once your Firebase project is configured, the next step is to add the required dependencies in your Flutter app. First step is to open the pubspec.yaml
file and add the following dependencies for Firebase and FCM:
dependencies:
firebase_core: latest_version
firebase_messaging: latest_version
After that, remember to run flutter pub get
to install the packages.
Configure Your Android and iOS Projects
Android Configuration
To enable FCM on Android, follow these steps:
- In the Firebase Console, download the
google-services.json
file and place it in yourandroid/app
directory. - Modify the
android/build.gradle
file:
dependencies {
classpath 'com.google.gms:google-services:latest_version'
}
- Update the
android/app/build.gradle
file by adding the following at the bottom:
apply plugin: 'com.google.gms.google-services'
iOS Configuration
For iOS, follow these steps:
- In the Firebase Console, download the
GoogleService-Info.plist
file and place it in yourios/Runner
directory. - Open the
ios/Runner.xcworkspace
file in Xcode and add the Firebase SDK to your project. - Make sure you’ve enabled push notifications in your Xcode project settings (under Capabilities).
Initialize Firebase and FCM in Your App
Now, initialize Firebase and FCM in your Flutter project.
- Open
lib/main.dart
and initialize Firebase in themain()
function:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
- Create an instance of
FirebaseMessaging
to listen for incoming notifications:
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
@override
void initState() {
super.initState();
// Request notification permissions (iOS specific)
_firebaseMessaging.requestPermission();
// Handle foreground notifications
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Received a notification: ${message.notification?.title}');
});
// Handle notification when the app is launched via a notification click
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Notification clicked! Redirecting to specific screen...');
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("FCM Demo")),
body: Center(child: Text("Waiting for notifications...")),
),
);
}
}
- onMessage: Handles notifications received while the app is in the foreground.
- onMessageOpenedApp: Handles clicks on notifications when the app is in the background or terminated.
Sending Your First Notification via Firebase Console
Now that your app is configured to receive notifications, let’s send a test notification from the Firebase Console.
- In the Firebase Console, go to the Cloud Messaging tab.
- Click on Send Your First Message.
- Create a message by filling in the notification title and body.
- Target the app by selecting Test on Device and entering the device token (you can retrieve the device token using
_firebaseMessaging.getToken()
). - Click Send Message to deliver the notification to your app.
You should now see the notification appear on your device.
Handling Notification Data Payload
Apart from displaying notifications, FCM allows you to send custom data in your messages. This can be useful for triggering in-app behaviors like navigation or updating the app state.
1. Sending Data Payload
In the Firebase Console, you can add custom data to your notification:
- Create a new message and scroll down to the Advanced Options.
- Add a key-value pair under the Custom Data section, e.g.,
"type": "promotion"
. - Send the message.
2. Handling Data Payload in Flutter
You can handle the custom data in your Flutter app using the RemoteMessage
object:
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (message.data.isNotEmpty) {
print('Data message: ${message.data}');
if (message.data['type'] == 'promotion') {
// Handle promotion-related logic here
}
}
});
This allows you to respond to specific data in the payload, such as triggering a special promotion screen or updating in-app content.
Handling Notifications When App is in Background or Terminated
Notifications behave differently when the app is in the background or terminated. You can handle these scenarios using the onBackgroundMessage
function:
- Add a background message handler:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print('Handling a background message: ${message.messageId}');
}
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
This ensures that notifications are handled even when the app is in the background.
Best Practices for Sending Notifications
- Targeted Notifications: Use Firebase audiences or topics to send notifications to specific groups of users.
- User Engagement: Be strategic with notifications—overloading users with too many messages can result in uninstalls or opt-outs.
- Silent Notifications: Use data-only messages to update the app content in the background without alerting the user.
Wrap Up
You’ve now successfully integrated Firebase Cloud Messaging into your Flutter app! You can now send real-time notifications, handle custom data payloads, and track user interactions. Push notifications are a key tool to increase user engagement, boost retention, and provide users with relevant, timely information.