Intermediate
Push Notifications (Firebase Cloud Messaging) Integration in Flutter
· 9 min read
How FCM Works
Firebase Cloud Messaging (FCM) delivers a message from your server (or the Firebase Console) to target devices through Google's infrastructure. Each device gets a unique 'device token' on install; your server sends messages to that token. How the app handles an incoming message depends on the app's current state (foreground, background, terminated) — and understanding the difference between these three states is exactly the most critical part of this article.
Setup and Requesting Permission
After adding the firebase_messaging package and calling Firebase.initializeApp(), notification permission must be explicitly requested on iOS and on Android 13 (API 33) and above; otherwise no notification will ever be shown to the user.
final messaging = FirebaseMessaging.instance;
final ayarlar = await messaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
if (ayarlar.authorizationStatus == AuthorizationStatus.authorized) {
final token = await messaging.getToken();
// token'ı backend'inize gönderin
}Three States: Foreground, Background, Terminated
• Foreground (app open and in front): the system does NOT show a notification automatically; you must listen to the FirebaseMessaging.onMessage stream and show it yourself (usually with flutter_local_notifications). • Background (app is backgrounded, not closed): the system shows the notification automatically. When the user taps it and brings the app to the front, FirebaseMessaging.onMessageOpenedApp fires. • Terminated (app fully closed): the system still shows the notification; when the app is opened by tapping it, you can find out which message opened the app with FirebaseMessaging.instance.getInitialMessage().
// Foreground: bildirimi kendiniz göstermelisiniz
FirebaseMessaging.onMessage.listen((RemoteMessage mesaj) {
yerelBildirimGoster(mesaj.notification?.title, mesaj.notification?.body);
});
// Kullanıcı bildirime dokunup uygulamayı açtı (arka plandan)
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage mesaj) {
_yonlendir(mesaj.data['route']);
});
// Uygulama tamamen kapalıyken bir bildirimle açıldıysa
final baslangicMesaji = await FirebaseMessaging.instance.getInitialMessage();
if (baslangicMesaji != null) {
_yonlendir(baslangicMesaji.data['route']);
}Background Handler: It Must Be a Top-Level Function
You can register a handler to process messages that arrive while the app is fully closed or backgrounded, but this function MUST be a top-level function — outside any class — and marked with @pragma('vm:entry-point'), because this code runs in a separate isolate, without the app's main widget tree ever starting up.
@pragma('vm:entry-point')
Future<void> arkaPlanMesajHandler(RemoteMessage mesaj) async {
await Firebase.initializeApp();
print('Arka planda mesaj alındı: ${mesaj.messageId}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(arkaPlanMesajHandler);
runApp(const MyApp());
}Subscribing to a Topic
Instead of messaging every user individually, you can group them by interest using topics. Once a user subscribes to a topic, they receive every message sent to it, with no need to know their token.
await FirebaseMessaging.instance.subscribeToTopic('flutter-haberleri');
// Abonelikten çıkmak için:
// await FirebaseMessaging.instance.unsubscribeFromTopic('flutter-haberleri');Things to Watch Out For
• Testing push notifications on iOS requires a real device and a properly configured APNs certificate/key in your Apple Developer account; push notifications may partially work in the simulator (from iOS 16 onward), but production testing should always be done on a real device. • The device token can change over time (app reinstall, data cleared); listen to the FirebaseMessaging.instance.onTokenRefresh stream to keep your backend up to date. • Never put sensitive user data (passwords, full card numbers, etc.) in notification content; notifications can even show up on the device's lock screen.
Conclusion
The most critical part of FCM integration is that messages are handled differently depending on whether the app is in the foreground, background, or terminated. Request permission, show the notification yourself in the foreground, define the background handler as a top-level function, and remember to keep the token up to date.