How to Add Push Notifications to a Flutter App with Firebase (FCM)

A practical tutorial for Flutter push notifications with Firebase Cloud Messaging — APNs setup, permissions, tokens, foreground and background messages, and deep links.

Darko Bačić, authorDarko Bačić 4 min read
On this page
  1. Prerequisites
  2. 1. Connect Firebase to the app
  3. 2. iOS setup: APNs key and capabilities
  4. 3. Ask for permission at the right moment
  5. 4. Get and store the device token
  6. 5. Handle messages in every app state
  7. 6. Deep link to the right screen
  8. 7. Send a test message
  9. Troubleshooting checklist

Push notifications are one of the few ways to bring users back to your app without paying for ads. They're also a classic source of "works on Android, silent on iOS" bugs.

This tutorial covers a production-ready setup with Firebase Cloud Messaging (FCM), which delivers to both Android and iOS (via Apple Push Notification service).

##Prerequisites

  • A Flutter app and a Firebase project
  • The FlutterFire CLI (dart pub global activate flutterfire_cli)
  • A paid Apple Developer account (required for iOS push)
  • A real iPhone — the iOS Simulator has limited push support, so test on a device

##1. Connect Firebase to the app

bash
flutter pub add firebase_core firebase_messaging
flutterfire configure

flutterfire configure registers your iOS and Android apps in Firebase and generates firebase_options.dart. Then initialize Firebase before runApp:

dart
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}

##2. iOS setup: APNs key and capabilities

iOS is where most push setups break. Do these three things:

  1. 01In the Apple Developer portal, create an APNs Authentication Key (.p8) under Keys. Note the Key ID and your Team ID.
  2. 02In the Firebase console → Project settings → Cloud Messaging → your iOS app, upload the .p8 key with its Key ID and Team ID.
  3. 03In Xcode, open ios/Runner.xcworkspace, select the Runner target → Signing & Capabilities, and add Push Notifications and Background Modes → Remote notifications.

##3. Ask for permission at the right moment

On iOS (and Android 13+), users must grant permission. Don't ask on first launch with no context — ask right after the user does something where notifications clearly help ("Notify me when my order ships").

dart
final messaging = FirebaseMessaging.instance;

Future<bool> requestPushPermission() async {
  final settings = await messaging.requestPermission(
    alert: true,
    badge: true,
    sound: true,
  );
  return settings.authorizationStatus == AuthorizationStatus.authorized ||
      settings.authorizationStatus == AuthorizationStatus.provisional;
}
A short screen explaining *why* before the system prompt ("We'll only notify you about your bookings") noticeably improves opt-in rates. You only get one system prompt on iOS — if the user declines, they have to enable it in Settings.

##4. Get and store the device token

Each install gets an FCM registration token. Send it to your backend so you can target this user, and update it when it changes:

dart
Future<void> syncPushToken(String userId) async {
  final token = await FirebaseMessaging.instance.getToken();
  if (token != null) await api.saveDeviceToken(userId, token);

  FirebaseMessaging.instance.onTokenRefresh.listen((newToken) {
    api.saveDeviceToken(userId, newToken);
  });
}

Store tokens per device, not per user — people use multiple devices. Remove tokens your backend gets "unregistered" errors for.

##5. Handle messages in every app state

A message can arrive while the app is in the foreground, in the background, or terminated. Each needs handling.

dart
// Must be a top-level function.
@pragma('vm:entry-point')
Future<void> firebaseBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  // Keep this light: update local data, no UI.
}

void setupPushHandlers() {
  FirebaseMessaging.onBackgroundMessage(firebaseBackgroundHandler);

  // App open in the foreground
  FirebaseMessaging.onMessage.listen((message) {
    // By default, notifications aren't shown while the app is in the foreground.
    // Show an in-app banner, or use flutter_local_notifications.
  });

  // User tapped a notification while the app was in the background
  FirebaseMessaging.onMessageOpenedApp.listen(openFromMessage);
}

Future<void> handleLaunchFromNotification() async {
  // User tapped a notification while the app was terminated
  final initial = await FirebaseMessaging.instance.getInitialMessage();
  if (initial != null) openFromMessage(initial);
}

To show heads-up notifications on iOS while the app is open, you can also call:

dart
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
  alert: true, badge: true, sound: true,
);

A notification that opens the home screen is a wasted tap. Put a route in the message's data payload and navigate on open:

dart
void openFromMessage(RemoteMessage message) {
  final route = message.data['route']; // e.g. "/orders/123"
  if (route != null) router.push(route);
}

##7. Send a test message

The quickest test is the Firebase console → Messaging → "Send test message" with your device token. For real sends, use the FCM HTTP v1 API or the Firebase Admin SDK from your backend, authenticated with a service account — the old legacy server-key API has been shut down.

##Troubleshooting checklist

  • Nothing arrives on iOS: check the APNs key is uploaded to the right Firebase app, the Push Notifications capability is enabled, and you're testing on a real device.
  • Arrives in background but not foreground: that's expected — handle onMessage or set foreground presentation options.
  • Background handler never runs: it must be a top-level function annotated with @pragma('vm:entry-point').
  • Android 13+ shows nothing: you haven't requested the notification permission.
  • Works in debug, not release: check that release signing and the APNs environment match, and that the release build was uploaded through TestFlight.

Monetizing the app too? Pair this with our RevenueCat subscription tutorial to re-engage trial users before their trial ends.

##Frequently asked questions

Is Firebase Cloud Messaging free?+

Yes, FCM itself is free to use. You may pay for other Firebase or cloud services your backend uses to decide when to send messages.

Do I need Firebase to send push notifications on iOS?+

No. iOS notifications are delivered by Apple's APNs; FCM is a convenient layer that lets you send to iOS and Android with one API. You can talk to APNs directly or use other providers.

Why do I need a real device to test iOS push?+

Simulator support for remote push is limited, and the full APNs delivery path is only reliably testable on a physical iPhone with a properly signed build.