Sub topic 1
How a push notification travels from server to device
This chapter explains the path a push message takes before it appears on a phone. You will not write much code here. The goal is a working mental model that the later chapters build on: setup, permissions, tokens, message types and handlers all map onto a stage in this path.
Prerequisites
This chapter assumes you have:
- Basic Dart and Flutter app structure: widgets,
async/awaitand streams. - A Flutter project that builds and runs on an emulator or device.
- A Google account, and either a Firebase project or willingness to create one.
- Basic familiarity with Android and iOS project files, such as
AndroidManifest.xmland Xcode capabilities.
You do not need any Firebase experience.
Why push notifications need a middleman
A push notification is a message that reaches a device even when your app is not running. An app cannot keep its own always-open connection to your server in the background. Mobile operating systems limit background work to save battery, and they stop apps that hold connections open.
The operating system solves this by running one shared, always-on connection of its own. Every app on the device uses that connection. Apple runs the service for iOS, called the Apple Push Notification service (APNs). Google runs the service for Android, which is Firebase Cloud Messaging (FCM) itself, delivered through Google Play services on the device.
Firebase Cloud Messaging is a Google service that accepts messages from your server and routes them to devices. It is also the layer you use from Flutter on both platforms. On Android, FCM delivers to the device directly. On iOS, FCM hands the message to APNs, because only APNs can reach an iPhone.
The main parts
The path involves five parts. Learn their names, because error messages and documentation use them.
| Part | What it is | Who runs it |
|---|---|---|
| Sender | Your server code, a cloud function, or the Firebase console. It decides who gets a message and what it says. | You |
| FCM backend | Accepts send requests, authenticates them, and finds the target devices. | |
| Platform service | On Android, the FCM connection on the device. On iOS, APNs. | Google or Apple |
| Device operating system | Receives the message and either shows it or hands it to your app. | Google or Apple |
| Your Flutter app | Uses the `firebase_messaging` plugin to read tokens and handle messages. | You |
The journey step by step
The diagram starts with the app because a message can only be sent to a device that has registered. The steps are:
- Registration. When the app starts, the
firebase_messagingplugin asks FCM for a registration token. A registration token is a string that identifies one app installation on one device. On iOS, FCM first needs an APNs token from Apple and links the two. - Token storage. The app sends the token to your server, or you copy it by hand while testing. FCM does not tell your server about devices on its own.
- Send request. Your server calls FCM and names a target, which is usually a token or a topic. It also provides a payload, the content of the message.
- Routing. FCM checks the request and finds the device. On iOS it forwards the message to APNs. On Android it uses its own connection.
- Delivery. The platform service delivers the message to the device over the shared connection. If the device is offline, the service holds the message and retries until it expires.
- Presentation. The operating system or your app decides what the user sees. This last step depends on the message type and on the app state.
What the payload contains
A payload is the data carried by a message. FCM supports two kinds, and later chapters cover them in detail. For now, know that they behave differently:
- A notification message has fields such as a title and body. The operating system can display it for you when the app is in the background.
- A data message has only custom key-value pairs. It never displays by itself. Your app code must read it and decide what to do.
A message can carry both. The following request body, for the FCM HTTP v1 send endpoint, shows one:
{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"notification": {
"title": "Order shipped",
"body": "Your order #42 is on its way."
},
"data": {
"route": "/orders/42"
}
}
}The token field is the target. The notification block is the part the system can display. The data block is for your app, and its values must be strings.
The three app states
Your app is always in one of three states when a message arrives. The state decides which code runs.
| State | Meaning | Where your code receives the message |
|---|---|---|
| Foreground | The app is open and visible. | A stream listener in the running app |
| Background | The app is not visible, but the process is still alive. | The operating system for display, plus a handler for taps or data |
| Terminated | The user closed the app, or the system stopped it. | The operating system for display, and a separate handler started on demand |
A foreground message is the surprising case. When the app is visible, the operating system does not show a notification banner for you by default. Your app receives the message and must choose how to show it. Many developers expect a banner and see nothing. This is the first item to check when "notifications do not work" only while the app is open.
Where each piece lives in your Flutter project
Each stage of the path corresponds to something you configure or write:
- Firebase project and options. You connect the app to a Firebase project, and the FlutterFire CLI generates
firebase_options.dart. - Platform setup. Android needs a manifest permission on newer versions. iOS needs push capabilities and an APNs key uploaded to Firebase.
- Permission. Android 13 and later, and all iOS versions, require the user to allow notifications.
- Token code. Your app reads and refreshes the registration token.
- Handlers. Streams and a top-level background function receive messages.
The following code shows the shape of the app entry point. It initializes Firebase and registers a background handler. The handler must be a top-level function so the system can start it in its own isolate, which is a separate Dart execution context with its own memory.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
// Must be a top-level function so it can run in its own isolate.
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
debugPrint('Background message: ${message.messageId}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('FCM demo')))));
}The handler calls Firebase.initializeApp again because the isolate does not share memory with the main one. Without that call, any Firebase use inside the handler fails.
Failure points along the path
Knowing the path tells you where to look when a message does not arrive. Work from the sender toward the app:
- Sender. The request is rejected, for example because of bad credentials or a malformed payload. FCM returns an error response, so check it first.
- Token. The token is stale, from another Firebase project, or from an uninstalled app. FCM reports that the target is not registered.
- APNs link (iOS only). The APNs key is missing from Firebase, or the push capability is missing in Xcode. FCM accepts the request, but nothing reaches the phone.
- Device. The device is offline past the message's lifetime, or battery and background restrictions delay delivery.
- Permission. The user denied notifications, so the operating system hides everything.
- App code. The message arrived, but the handler is missing, is not top-level, or shows nothing in the foreground.
What FCM does not do
FCM is a transport, so some jobs stay with you:
- It does not store the list of your users' tokens. You keep that on your server.
- It does not decide when a user should be notified. Your server logic does.
- It does not guarantee delivery or timing. Messages can be delayed, collapsed or dropped when they expire.
- It does not draw notifications in the foreground. Your app does.
Later chapters return to each of these: token storage, topics for group sends, local notifications for foreground display, and the delivery limits that explain missing messages.
Summary of the model
A sender gives FCM a target and a payload. FCM routes it through the platform service, which is FCM itself on Android and APNs on iOS, to the device operating system. The operating system or your Flutter app then presents it, depending on the message type and the app state. Every later chapter configures or handles one of these links.
Exercise
A user reports that your iOS app never receives notifications. The Firebase console shows the send request as accepted. Name the stage of the path you should check first for iOS-specific problems, and give two things you would verify there.
Show answer
Check the APNs link between FCM and the device. Verify that an APNs authentication key (or certificate) is uploaded to the Firebase project settings, and that the Push Notifications capability is enabled for the app in Xcode. You should also confirm the user granted notification permission, since FCM accepting the request only proves the first steps worked.
Exercise
Your app is open on screen and a message with a notification block arrives. No banner appears, but your onMessage listener runs. Is this a bug in the setup? Explain, and say where the display responsibility lies.
Show answer
No. In the foreground, the operating system does not show a banner for FCM notification messages by default. The app receives the message through its stream listener and is responsible for presenting it, for example by updating the UI or showing a local notification.