initialize method
Future<void>
initialize({
- required void onMessage(
- PushMessage message
- required void onMessageOpenedApp(
- PushMessage message
- void onTokenRefresh(
- String? token
Initializes FCM message handling.
Requests permission on iOS/web, subscribes to foreground and background-opened-app streams, and handles messages that launched the app from a terminated state.
onMessage is called when a push arrives while the app is in the
foreground.
onMessageOpenedApp is called when the user taps a notification that
was displayed while the app was in the background or terminated.
onTokenRefresh is called when the FCM token is created or rotated.
Use this to send the updated token to your backend.
Implementation
Future<void> initialize({
required void Function(PushMessage message) onMessage,
required void Function(PushMessage message) onMessageOpenedApp,
void Function(String? token)? onTokenRefresh,
}) async {
if (_initialized) {
PrimekitLogger.warning(
'PushHandler.initialize() called more than once. Ignoring.',
tag: _tag,
);
return;
}
_onMessage = onMessage;
_onMessageOpenedApp = onMessageOpenedApp;
// Request permission (iOS / web).
await FirebaseMessaging.instance.requestPermission(
alert: true,
badge: true,
sound: true,
);
// Foreground messages.
FirebaseMessaging.onMessage.listen((RemoteMessage msg) {
onMessage(_fromRemote(msg));
});
// Background → foreground tap.
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage msg) {
onMessageOpenedApp(_fromRemote(msg));
});
// Token refresh.
FirebaseMessaging.instance.onTokenRefresh.listen((token) {
onTokenRefresh?.call(token);
});
// Check for notification that launched the app from terminated state.
final initial = await FirebaseMessaging.instance.getInitialMessage();
if (initial != null) {
onMessageOpenedApp(_fromRemote(initial));
}
_initialized = true;
PrimekitLogger.info('PushHandler initialized.', tag: _tag);
}