Push

Flutter Push Notifications: The Complete Guide for Android and iOS

9:41

Flutter push notifications use Firebase Cloud Messaging (FCM) on both Android and iOS. You add the Firebase packages, register the device to get an FCM token, and send messages to that token from a server. Android needs a manifest entry and, on Android 13 and later, a runtime permission. iOS needs an APNs key in Firebase, the Push Notifications capability and, if you want to know whether a notification was delivered while the app was closed, a Notification Service Extension. This guide walks through all of it with flutter_notify_sphere, then covers the three app states, taps and deep links, images and sounds, attribution, and the errors you're most likely to hit.

How push notifications work in Flutter

There are four parties: your Flutter app, Firebase Cloud Messaging, Apple Push Notification service (APNs) for iPhones, and the server that sends the message.

  1. When the app starts, the Firebase SDK on the phone gets a registration token from FCM. On iOS it first needs an APNs token from Apple.
  2. The app sends that token to your push server, together with who the user is.
  3. When you send a campaign, the server calls the FCM API with the token and the message.
  4. FCM delivers to Android phones directly. For iPhones, FCM hands the message to APNs using the APNs key you uploaded to Firebase.
  5. The phone shows the notification, or passes it to your app, depending on the app's state.

Two things in that chain catch most people. Tokens change: when a user reinstalls the app or clears its data, the old token stops working, and FCM tells you so with an UNREGISTERED error. And FCM confirming that it accepted a message doesn't mean the phone ever showed it. If you want delivery numbers you can trust, the phone has to report back. That's what the SDK used in this guide does.

What you need

  • Flutter with Dart 3.9 or newer.
  • A Firebase project with your Android and iOS apps added.
  • For iOS: an APNs authentication key (.p8) from your Apple Developer account, uploaded in Firebase → Project settings → Cloud Messaging.
  • A notifySphere app with its App ID and API token, and your Firebase service account JSON uploaded (see push setup and Firebase credentials). It's free up to 1,000 monthly active users.
  • A real Android phone and a real iPhone for testing.

Step 1: Add the packages

Add the SDK and the two Firebase packages to pubspec.yaml, then run flutter pub get.

dependencies:
  flutter:
    sdk: flutter
  flutter_notify_sphere: ^1.2.1
  firebase_core: ^4.3.0
  firebase_messaging: ^16.1.0

flutter_notify_sphere 1.2.1 depends on firebase_core ^4.3.0 and firebase_messaging ^16.1.0. If your app pins older Firebase versions, pub get fails with “version solving failed”. Upgrade the Firebase packages together; mixing major versions of FlutterFire plugins causes the same error.

Step 2: Set up Android

Download google-services.json from the Firebase console into android/app/ and apply the Google Services Gradle plugin, as the FlutterFire setup describes. Then add the permissions and the default icon and channel to android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.VIBRATE"/>

<application ...>
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@mipmap/ic_launcher" />
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="notify_sphere_channel" />
</application>

The notification permission. Since Android 13, apps must ask the user before showing notifications, and the request only works if POST_NOTIFICATIONS is in the manifest. You don't need to request it yourself: registerUser() asks for permission before it gets the token. If the user says no, the device still registers, but nothing is shown. The Android 13 notification permission guide covers when to ask and what to do after a denial.

The icon. Android draws the small notification icon as a single-color silhouette. A full-color launcher icon often shows as a plain white shape, so point default_notification_icon at a simple, transparent icon once you have one.

Custom sounds. Put the sound file in android/app/src/main/res/raw/, for example custom_sound.mp3, and enter custom_sound without the extension in the campaign's sound field.

Step 3: Set up iOS

Open ios/Runner.xcworkspace in Xcode and add GoogleService-Info.plist to the Runner folder. Then, under Signing & Capabilities for the Runner target, add:

  • Push Notifications, so iOS gives the app an APNs token.
  • Background Modes with Remote notifications and Background fetch.
  • App Groups with a group named group.<your.bundle.id>. The extension in the next step uses it to read the credentials the SDK saves.

If iOS push doesn't work later, this step is usually why. A missing capability gives you “No APNS token specified”, and an APNs key problem in Firebase gives you THIRD_PARTY_AUTH_ERROR on every iOS send while Android keeps working. The Firebase iOS push setup guide goes through the APNs key step by step.

Step 4: Add a Notification Service Extension

This is the step most Flutter push tutorials leave out. When a notification arrives while your app is in the background or closed, iOS shows it without running any of your Dart code. So the app can't report that it arrived, and it can't download an image to attach.

A Notification Service Extension is a small native target that iOS runs for each incoming notification marked mutable-content. In Xcode, choose File → New → Target → Notification Service Extension (Swift), name it, for example, ImageNotification, and give it the same App Group as Runner. Then add NotifySphereExtension.swift to it and call it from NotificationService.swift; both files are in the package README. The extension reads the App ID and API key from the shared App Group, confirms delivery, attaches the image and applies a custom sound.

Without it, iOS notifications still arrive, but deliveries while the app is closed aren't counted and images don't show.

Step 5: Initialize the SDK

Initialize Firebase, then the SDK, before runApp:

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_notify_sphere/flutter_notify_sphere.dart';

// Must be a top-level function, not a method or a closure
@pragma('vm:entry-point')
Future<void> backgroundMessageHandler(RemoteMessage message) async {
  // Runs in a separate isolate: no widgets, no app state. Keep it short.
}

final navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  await FlutterNotifySphere().initialize(
    showForegroundNotification: true,
    onForegroundMessage: (RemoteMessage message) {
      debugPrint('Push while the app is open: ${message.data}');
    },
    onNotificationClick: (RemoteMessage? message) {
      final screen = message?.data['screen'];
      if (screen != null) navigatorKey.currentState?.pushNamed(screen);
    },
    backgroundMessageHandler: backgroundMessageHandler,
    useReferral: true, // read the TrackerLink install referrer (default true)
  );

  runApp(MaterialApp(navigatorKey: navigatorKey, home: const HomeScreen()));
}

A few rules here save hours later:

  • The background handler must be a top-level function with @pragma('vm:entry-point'). It runs in a separate isolate, without your widgets or app state, and the annotation stops the release build from removing it.
  • Pass your handler to the SDK instead of calling FirebaseMessaging.onBackgroundMessage yourself. The SDK registers its own background handler, which records the delivery and then calls yours.
  • Navigate through a navigator key. A tap that starts the app can arrive before your first screen has a usable BuildContext. A GlobalKey<NavigatorState> works from anywhere.

Step 6: Register the user and device

registerUser() asks for notification permission, gets the FCM token and sends it to notifySphere with the user's details. Call it once you know who the user is, for example after sign-in:

// After login, or on the screen where asking for permission makes sense
await FlutterNotifySphere().registerUser(
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_API_TOKEN',
  userData: {
    'applicationUserId': 12345, // your own user ID
    'name': 'Jane Doe',
    'email': 'jane@example.com',
    // Always pass a tags map: the SDK adds the TrackerLink click to it
    'tags': <String, dynamic>{'plan': 'free'},
  },
  onFcmToken: (String? token) => debugPrint('FCM token: $token'),
  onRegistrationComplete: (String? id) => debugPrint('Subscription: $id'),
  onError: (Object error) => debugPrint('Registration failed: $error'),
);
  • Permission timing matters. Because this call shows the permission prompt, calling it on the very first screen means asking before the user knows why. After sign-up, or after the user turns on a feature that needs notifications, is usually better.
  • Always pass a tags map, even an empty one. If the user installed from a TrackerLink, the SDK adds the campaign click to tags.
  • On iOS, the SDK waits up to 10 seconds for the APNs token before asking for the FCM token. If it never arrives, onFcmToken gets no token. That almost always means the Push Notifications capability is missing or you're not on a real device.
  • Nothing is lost before registration. If a notification is delivered or tapped before registerUser() finishes, for example a tap that starts the app, the event is queued and sent once registration completes.

Foreground, background and terminated: what happens

Most “push doesn't work” reports are really “push works differently in this app state”. Here is what happens to a notification in each state with this setup:

App stateAndroidiOSYour code that runs
Foreground (app open)Not shown by the system. The SDK shows it as a local notification, with its image, when showForegroundNotification is true.Shown, because the SDK sets the foreground presentation options to alert, badge and sound.onForegroundMessage
Background (app in memory)Shown in the tray by the system.Shown by the system.Your backgroundMessageHandler, then onNotificationClick on tap
Terminated (swiped away or not started)Shown by the system, unless the phone's battery settings stop the app.Shown by the system. Delivery is confirmed by the Notification Service Extension.onNotificationClick when a tap starts the app

Include a notification block, not data only. A message with a top-level notification block is shown by the system even when your app isn't running. A data-only message depends on your app waking up to show it, which Android battery savers and iOS background limits often prevent. The notifySphere docs recommend mixed payloads: notification for the system to display, and data for tracking and routing. If notifications still go missing when the app is closed, work through Flutter push notifications not received in background.

Handling taps and deep links

A tap can reach your app in two ways. If the app was in the background, Firebase fires onMessageOpenedApp. If the tap started the app, the message comes from getInitialMessage(). The SDK listens to both and calls your onNotificationClick once per tap, so you don't handle the two cases separately.

On iOS there's a third case that loses taps with plain firebase_messaging. A push marked content-available can make iOS start a closed app in the background. Firebase then treats that push as the app's initial notification, so when the user taps it later, neither onMessageOpenedApp nor the earlier getInitialMessage() call delivers the tap. The SDK asks again when the app comes to the foreground, so these taps still reach onNotificationClick.

To open a specific screen, put a value in the notification's data, such as screen or orderId, and read it in onNotificationClick, as in the Step 5 example.

Images and custom sounds

  • Android, app open: the SDK downloads the message's imageUrl and shows it as an expandable big-picture notification, with the campaign's sound.
  • Android, app in background or closed: the system shows the notification itself, using the channel and the default icon from the manifest.
  • iOS: images and custom sounds come from the Notification Service Extension. No extension, no image.
  • Keep images small and on HTTPS. The extension only has a short time to download them before iOS shows the notification without the image.

Tracking conversions and campaigns

Since version 1.2, the Flutter SDK also does attribution with TrackerLink. With useReferral: true (the default), it reads the campaign click on first launch from the Google Play install referrer on Android. (On iOS, where there is no install referrer, notifySphere matches the install to a recent click from the same IP address or device.) The click is saved and sent with the user's tags at registration. After that you can record conversions and change tags:

// A conversion, for campaign attribution
await FlutterNotifySphere().postEvent(
  event: 'purchase',
  data: {'revenue': 499, 'order_id': 'ORD123'},
);

// Change the user's tags without registering again
await FlutterNotifySphere().updateTags(
  tags: {'plan': 'pro'},
);

postEvent() needs registerUser() to have completed; before that it returns false. updateTags() merges the new tags into the existing ones. Opening a specific screen from a deep link is still up to your app. Not sure how a link survives the install? Deferred deep linking explained covers both platforms.

Step 7: Test on real devices

Send a test campaign from the dashboard and check each state on both platforms:

  1. App open: a notification appears and onForegroundMessage fires.
  2. App in background: the notification is in the tray; tapping it fires onNotificationClick and the Clicked count goes up.
  3. App swiped away: the notification still shows. On iOS, the Delivered count goes up, which proves the extension works.
  4. Tap from closed: the app opens on the right screen.
dashboard.notifysphere.net
notifySphere dashboard with active subscriptions, app subscribers, monthly active users, and push sends
Registered Flutter devices appear as app subscribers, with sends, deliveries and clicks per campaign.

Building the payload yourself instead of sending from the dashboard? The FCM payload builder creates the HTTP v1 JSON, and the push notification preview shows where the text gets cut on Android and iPhone.

Troubleshooting

SymptomUsual causeFix
version solving failedFirebase packages older than the SDK needsUse firebase_core ^4.3.0 and firebase_messaging ^16.1.0 or newer in the same major version
No permission prompt on Android 13+POST_NOTIFICATIONS missing from the manifestAdd the permission; the prompt appears when registerUser() runs
Nothing arrives on iOS, Android worksAPNs key missing, revoked or for the wrong teamUpload the .p8 key in Firebase → Cloud Messaging. See THIRD_PARTY_AUTH_ERROR
“No APNS token specified” in the logsFCM token requested before iOS gave an APNs tokenCheck the Push Notifications capability and test on a real device
Delivered count stays at 0 when the iPhone app is closedNo Notification Service Extension, or a different App GroupAdd the extension and give it the same App Group as Runner
Background handler never runsNot a top-level function, or no vm:entry-point annotationMove it to the top level of a file and add @pragma('vm:entry-point')
Tap opens the app but not the right screenNavigation runs before the navigator existsNavigate through a GlobalKey<NavigatorState>, as in the Step 5 example
Sends fail with UNREGISTEREDThe app was uninstalled or the token was replacedStop sending to that token. See FCM UNREGISTERED

Getting an error code back from FCM or APNs? The FCM and APNs error code table explains each one and whether to delete the token. Notifications arriving late rather than not at all? See why push notifications arrive late.

Frequently asked questions

Do I need Firebase for Flutter push notifications?

On Android, yes: push goes through Firebase Cloud Messaging. On iOS, Apple's APNs delivers the notification, but most Flutter apps still use FCM in front of it so one token and one API work for both platforms. That's what firebase_messaging and flutter_notify_sphere do.

Why don't push notifications show when my Flutter app is open?

Android doesn't display notification messages while the app is in the foreground; the app has to show them itself. flutter_notify_sphere does this with a local notification when showForegroundNotification is true. On iOS the SDK sets the foreground presentation options so the system shows them.

When does the notification permission prompt appear?

With flutter_notify_sphere, registerUser() asks for notification permission before it gets the FCM token. Call it at a point where the user understands why you're asking, for example after sign-up, rather than on the very first screen.

How do I open a specific screen when the user taps a notification?

Put the screen name or ID in the notification's data, and navigate in onNotificationClick using a GlobalKey<NavigatorState>. The SDK calls onNotificationClick for taps from the background and for taps that start the app from a terminated state.

How do I know if a push notification was delivered?

FCM only tells you it accepted the message, not that the phone showed it. flutter_notify_sphere reports delivery from the app on Android and from a Notification Service Extension on iOS, and reports taps, so the dashboard shows delivered and clicked counts per campaign.

Does the Flutter SDK support attribution and deep link campaigns?

Yes, since version 1.2. It reads the TrackerLink click from the Play install referrer on Android, sends it with the user's tags, and records conversions with postEvent. On iOS, installs are matched to recent clicks by IP address or device. Routing to a screen from a deep link is handled by your app.

Next steps

The Flutter SDK reference lists every option. Using React Native instead? See the React Native push notifications guide. Comparing push providers? Read notifySphere vs OneSignal.