initialize method

Future<void> initialize(
  1. BuildContext context
)

Initializes FCM notifications and sets up message handlers.

Requests notification permissions, saves the FCM token, and configures handlers for foreground messages, app-opened notifications, and initial messages.

Parameters:

  • context: The BuildContext used for showing SnackBars and navigation.

Returns: A Future<void> that completes when initialization is done.

Implementation

Future<void> initialize(BuildContext context) async {
  // Request permission (iOS requires this)
  NotificationSettings settings = await _firebaseMessaging.requestPermission(
    alert: true,
    badge: true,
    sound: true,
  );

  if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    print('User granted permission');
  }

  // Get and save the FCM token
  String? token = await _firebaseMessaging.getToken();
  if (token != null) {
    await _saveTokenToFirestore(token);
  }

  // Handle token refresh
  _firebaseMessaging.onTokenRefresh.listen(_saveTokenToFirestore);

  // Foreground message handler
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    print('Got a message whilst in the foreground!');
    if (message.notification != null) {
      _showSnackBar(
          context, message.notification!.title, message.notification!.body);
    }
  });

  // Handle message when app is opened from notification
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    print('Message clicked!');
    _navigateBasedOnMessage(context, message);
  });

  // Handle initial message (app opened from terminated state)
  RemoteMessage? initialMessage =
      await _firebaseMessaging.getInitialMessage();
  if (initialMessage != null) {
    _navigateBasedOnMessage(context, initialMessage);
  }
}