Sub topic 5
Getting and refreshing the FCM token
This chapter covers the registration token: what it identifies, how to read it, and how to react when it changes. It assumes you can build a Flutter app, use async/await and streams, and have already added firebase_core and firebase_messaging. It also assumes you have configured Android and iOS, including APNs, and requested notification permission in earlier chapters.
What the token is
An FCM registration token is a string that identifies one installation of your app on one device. FCM uses it as the address for a message. When you send to a token, FCM looks up which app instance owns it and routes the message through Android's own channel or through APNs on iOS.
Three properties matter in practice:
- The token belongs to an app instance, not to a user. One user with a phone and a tablet has two tokens.
- The token is not permanent. FCM can issue a new one at any time.
- The token is a credential for sending. Anyone who knows it and has your server credentials can message that device, so do not log it in production or share it in public bug reports.
Reading the token
Call getToken() on FirebaseMessaging.instance. It returns a Future<String?>. The result is nullable because FCM may not be able to produce a token yet.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
Future<String?> readToken() async {
final token = await FirebaseMessaging.instance.getToken();
debugPrint('FCM token: $token');
return token;
}Call it after Firebase.initializeApp() has completed. If you call it earlier, the plugin throws because the native Firebase app does not exist yet.
Order on iOS: the APNs token comes first
On iOS, FCM needs an APNs device token before it can create an FCM token. Apple issues the APNs token after the user grants permission and the app registers for remote notifications. If you call getToken() before that has happened, you may get an error such as apns-token-not-set, or null.
A defensive approach is to read the APNs token first and wait briefly for it:
import 'dart:io' show Platform;
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
Future<String?> getFcmTokenSafely() async {
final messaging = FirebaseMessaging.instance;
if (!kIsWeb && Platform.isIOS) {
String? apnsToken = await messaging.getAPNSToken();
var attempts = 0;
while (apnsToken == null && attempts < 5) {
await Future<void>.delayed(const Duration(seconds: 1));
apnsToken = await messaging.getAPNSToken();
attempts++;
}
if (apnsToken == null) {
debugPrint('APNs token not available yet.');
return null;
}
}
return messaging.getToken();
}A null here is a normal outcome, not a crash. Reasons include a denied permission, a simulator without APNs support, a missing push capability in Xcode, or a missing APNs key in the Firebase console. Treat it as "try again later" and rely on onTokenRefresh as well.
Order of operations
Put the token logic after permission handling. A reliable order is:
- Initialize Firebase.
- Request permission.
- If permission is granted (or provisional on iOS), read the token.
- Send the token to your server.
- Subscribe to
onTokenRefresh.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
Future<void> registerForPush() async {
final messaging = FirebaseMessaging.instance;
final settings = await messaging.requestPermission();
final allowed =
settings.authorizationStatus == AuthorizationStatus.authorized ||
settings.authorizationStatus == AuthorizationStatus.provisional;
if (!allowed) {
debugPrint('Notifications not allowed: ${settings.authorizationStatus}');
return;
}
final token = await getFcmTokenSafely();
if (token != null) {
await uploadToken(token);
}
messaging.onTokenRefresh.listen(uploadToken).onError((Object error) {
debugPrint('Token refresh error: $error');
});
}
Future<void> uploadToken(String token) async {
// Replace with a call to your backend.
debugPrint('Uploading token: $token');
}The helper getFcmTokenSafely is the one from the previous listing.
On Android, a denied permission on Android 13 and later means notifications are not shown, but a token is still issued. Do not assume that a token means the user will see anything.
When the token changes
The onTokenRefresh stream emits a new token string. FCM can rotate a token for several reasons:
| Cause | What happens |
|---|---|
| App reinstalled | A new token is issued on first launch. |
| User clears app data (Android) | The old token is invalidated, a new one is issued. |
| App restored on a new device | The old token does not carry over. |
| `deleteToken()` is called | The current token is invalidated, and a new one is issued on the next `getToken()`. |
| FCM rotates it | A new token is delivered through the stream. Timing is not under your control. |
Two details trip people up:
onTokenRefreshis a broadcast stream. If you are not listening at the moment it emits, you miss the event. Subscribe early in startup, not behind a screen the user may never open.- Always keep the subscription, and cancel it if the owning object is disposed. Listening twice causes duplicate uploads.
import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
class TokenService {
StreamSubscription<String>? _subscription;
void start(Future<void> Function(String token) onToken) {
_subscription?.cancel();
_subscription = FirebaseMessaging.instance.onTokenRefresh.listen(onToken);
}
Future<void> stop() async {
await _subscription?.cancel();
_subscription = null;
}
}Check on every launch
Do not rely only on the refresh stream. A refresh can occur while the app is not running, and you will not see the event. Calling getToken() on each launch, then comparing the value with what you last uploaded, covers this gap. If the value differs, upload it. Store the last uploaded token locally, for example with shared_preferences, to avoid redundant network calls.
Deleting the token
deleteToken() invalidates the current token. Use it when a user signs out, so that notifications meant for the previous account stop reaching that device.
import 'package:firebase_messaging/firebase_messaging.dart';
Future<void> signOutOfPush(Future<void> Function(String token) removeFromServer) async {
final messaging = FirebaseMessaging.instance;
final token = await messaging.getToken();
if (token != null) {
await removeFromServer(token);
}
await messaging.deleteToken();
}Order matters. Tell your server to drop the token first, then delete it locally. If the process dies between the two steps in the opposite order, the server keeps a dead token.
If you want to stop FCM from creating tokens automatically, setAutoInitEnabled(false) disables auto-initialization until you re-enable it. This is useful for apps that need explicit consent before any registration happens.
Common errors
getToken()returnsnullon iOS. The APNs token is missing. Check the Push Notifications capability, the APNs key uploaded in Firebase, and that you are on a physical device.- Token works in debug but not in release. On iOS, the APNs environment differs between development and production. Using a key (
.p8) in Firebase covers both. A certificate covers only one. - Messages go to the wrong user. The server still holds a token tied to a previous account on the same device. Remove it on sign-out.
- Sends return
UNREGISTEREDorNOT_FOUND. The token is no longer valid. Delete it from your database. - Many duplicate rows per user. The app inserts a token at each launch without checking. Make the server treat the token as a unique key.
Server-side shape
Keep the server model simple: one row per token, linked to a user, with a timestamp.
| Field | Purpose |
|---|---|
| `token` | Unique key. |
| `user_id` | Owner at the time of upload. |
| `platform` | `android` or `ios`, for diagnostics. |
| `updated_at` | Lets you remove stale rows later. |
When a token arrives that already exists under a different user, reassign it rather than adding a second row. Later chapters on server-side storage cover pruning in more detail.
Exercise
A user signs out of your app and another user signs in on the same phone. The second user starts receiving the first user's notifications. What went wrong, and what should the sign-out code do?
Show answer
The server still maps the device's token to the first user, and the token was never invalidated. On sign-out, first ask the server to remove (or reassign) the token, then call deleteToken() on FirebaseMessaging. On the next sign-in, call getToken() and upload the new token for the second user.
Exercise
Your iOS app calls getToken() right after requestPermission() and sometimes gets null or an apns-token-not-set error. Give two things to do so the app still ends up with a valid token.
Show answer
Wait for the APNs token with getAPNSToken() (retrying a few times) before calling getToken(), and subscribe to onTokenRefresh so the FCM token is uploaded when it becomes available. Also confirm the Push Notifications capability, the APNs key in the Firebase console, and that you test on a physical device.