This guide shows you exactly how to implement Firebase Push Notification Flutter, or Firebase Cloud Messaging (FCM) a Flutter app for Android and iOS. You’ll set up Firebase, request permissions, handle foreground/background/terminated states, receive device tokens, subscribe to topics, and test your notifications.
First, make sure Firebase is set up in your project. Once that’s done, we’ll add the required package to enable Firebase push notifications. Additionally, if you have faced any problem to setup the Firebase, read this blog article and watch this video.
Install packages
Add these to pubspec.yaml
:
dependencies: firebase_core: ^latest firebase_messaging: ^latest # Optional but handy on Android 13+ for runtime permission prompt permission_handler: ^latest # Optional: show local notifications when app is foregrounded flutter_local_notifications: ^latest
After adding the package, don’t forget to run flutt pub get
Next, we will start to set up the environment for both Android and iOS according to the package.
Android Configuration for Firebase Push Notification
Notification permission (Android 13+)
- Add to
android/app/src/main/AndroidManifest.xml
:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
- Default notification icon/color (recommended to avoid a white square icon):
- Place a monochrome small icon (e.g.,
ic_stat_notification.png
) inandroid/app/src/main/res/drawable/
. - Under
<application>
inAndroidManifest.xml
add:<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_stat_notification" /> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/notification_color" />
- Define
notification_color
inandroid/app/src/main/res/values/colors.xml
If you use it. - Min SDK: Ensure
minSdkVersion
is at least 24 inandroid/app/build.gradle
.
IOS Configuration for Firebase Push Notification
- Open the iOS module in Xcode (
open ios/Runner.xcworkspace
). - Capabilities → enable Push Notifications and Background Modes → check Remote notifications.
- In the Firebase Console → Project settings → Cloud Messaging:
- Upload your APNs Authentication Key (.p8).
- Provide Key ID and Apple Team ID.
- In your Flutter code, request notification permission on iOS (see below) and set foreground presentation options.
Notes
- Use a physical iOS device to receive notifications.
- For debug builds, you can use the same APNs key; no need for separate development/production certificates when using the key method.
Initialize Firebase & FCM in Flutter
Create lib/firebase_push.dart
(or in main.dart
). Ensure the background handler is top-level.
// Must be a top-level function @pragma('vm:entry-point') Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async { await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); // Handle background message (log, analytics, local DB, etc.) debugPrint('BG message: \\${message.messageId} data=\\${message.data}'); } Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); // Register background handler before `runApp` FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); runApp(const MyApp()); }
Foreground, background & terminated handling
- Foreground:
FirebaseMessaging.onMessage
fires. Show your own local notification (because system banners often do not appear while the app is in the foreground). - Background: When the app is in the background, clicking a notification triggers
onMessageOpenedApp
. - Terminated: Fetch the initial message when the app starts:
-
Future<void> checkInitialMessage() async { final initialMessage = await FirebaseMessaging.instance.getInitialMessage(); if (initialMessage != null) { // Navigate based on payload } }
Call
checkInitialMessage()
Listen and Handle Notifications
Handle messages in different app states (foreground, background, and terminated):
FirebaseMessaging.onMessage.listen((RemoteMessage message) { // Handle foreground messages print('Received message: ${message.notification?.title}'); }); FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { // Handle notification opened from background or terminated state print('Notification clicked: ${message.notification?.title}'); });
Display Local Notifications
Use flutter_local_notifications
package to display notifications when the app is in the foreground:
- Initialize the local notifications plugin.
- Show notifications manually in the
onMessage
listener.
Get device token & subscribe to topics
final token = await FirebaseMessaging.instance.getToken(); // print this token. print('Device FCM Token: $token'); // Also Send this token to your backend to send targeted notifications (if required) await FirebaseMessaging.instance.subscribeToTopic('offers');
Tip: Tokens can rotate. Keep them in sync by updating your backend when onTokenRefresh
emitting.
FirebaseMessaging.instance.onTokenRefresh.listen((new()))
Test Push Notifications
- Use Firebase Console to send a test notification to your device using the FCM token.
- Confirm the notification appears in different app states.
- Use a real device to get notifications in real time.
In conclusion, this comprehensive step-by-step guide will help Flutter developers integrate powerful push notifications with Firebase Cloud Messaging or Firebase Push Notification Flutter, which enhances app user retention and engagement.