Sub topic 5
Getting and Refreshing the FCM Token
Assume you know basic Flutter app structure, Dart async/await, streams, and how to add packages to a Flutter project. This chapter assumes Firebase is already connected to your Android and iOS apps.
An FCM registration token identifies one app installation on one device. Your server uses the token as the destination when it sends a message. A token is not a user ID, an authentication credential, or a permanent device identifier.
Requesting a token
Add firebase_messaging to your project:
dependencies:
firebase_core: ^latest
firebase_messaging: ^latestInitialize Firebase before using FirebaseMessaging. On iOS and on Android versions that require runtime permission, ask the user for notification permission first.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
Future<void> setUpMessaging() async {
final messaging = FirebaseMessaging.instance;
final settings = await messaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
if (settings.authorizationStatus == AuthorizationStatus.denied) {
debugPrint('Notification permission denied');
return;
}
final token = await messaging.getToken();
if (token == null) {
debugPrint('FCM has not produced a token yet');
return;
}
debugPrint('FCM token: $token');
// Send the token to your application server here.
}getToken() is asynchronous because FCM may need to contact its service and the platform push service. It can return null, so do not force-unwrap the result.
The token can change after reinstalling the app, clearing app data, restoring a device backup, or when FCM rotates credentials. Listen for changes and update the server record.
void listenForTokenChanges() {
FirebaseMessaging.instance.onTokenRefresh.listen(
(newToken) {
debugPrint('FCM token refreshed: $newToken');
// Replace the old token on your server.
},
onError: (Object error) {
debugPrint('Token refresh failed: $error');
},
);
}Register this listener during app startup. It does not replace the initial getToken() call. You need both because the listener reports future changes, not necessarily the current token.
Store tokens on the server
Send the token over an authenticated HTTPS request. Associate it with the signed-in user and a device record. A user may have several tokens because they may use multiple devices or reinstall the app.
| Server value | Purpose |
|---|---|
| User ID | Identifies the account that owns the installation |
| FCM token | Destination for messages |
| Platform | Helps diagnose Android and iOS behavior |
| Last-seen time | Shows whether the installation is still active |
When a user signs out, remove or disassociate that device token. Never treat possession of an FCM token as proof of identity.
Token lifecycle
A failed message can indicate that a stored token is no longer valid. Your server should remove that token when the FCM response identifies it as unregistered. Do not repeatedly retry a permanently invalid token.
Exercise
Why should an app call both getToken() and listen to onTokenRefresh?
Show answer
getToken() obtains the current token during startup. onTokenRefresh reports later changes, so the server can replace its stored destination.