initialize method

Future<void> initialize({
  1. NotificationActionCallback? onNotificationTapped,
  2. NotificationButtonActionCallback? onNotificationAction,
  3. ForegroundMessageCallback? onForegroundMessage,
  4. NotificationErrorCallback? onError,
  5. bool showNotificationsInForeground = true,
  6. int reminderIntervalDays = 30,
})

Initializes the notification service.

This method sets up all notification handling including:

  • Local notification plugin initialization
  • FCM message listeners (foreground, background, terminated)
  • Notification action handlers
  • Platform-specific configuration

This is the only method consuming apps need to call to set up notifications.

Parameters:

  • onNotificationTapped: Callback for when user taps a notification
  • onNotificationAction: Callback for when user taps an action button
  • onForegroundMessage: Callback for when notification arrives in foreground
  • onError: Callback for handling errors
  • showNotificationsInForeground: Whether to display notifications in foreground (default: true)
  • reminderIntervalDays: Days between permission reminders (default: 30)

Example:

await NotificationService().initialize(
  onNotificationTapped: (route, data) async {
    if (route != null) {
      Navigator.of(context).pushNamed(route, arguments: data);
    }
  },
  showNotificationsInForeground: true,
);

Implementation

Future<void> initialize({
  NotificationActionCallback? onNotificationTapped,
  NotificationButtonActionCallback? onNotificationAction,
  ForegroundMessageCallback? onForegroundMessage,
  NotificationErrorCallback? onError,
  bool showNotificationsInForeground = true,
  int reminderIntervalDays = 30,
}) async {
  if (_initialized) {
    logi('NotificationService already initialized');
    return;
  }

  try {
    _onNotificationTapped = onNotificationTapped;
    _onNotificationAction = onNotificationAction;
    _onForegroundMessage = onForegroundMessage;
    _onError = onError;
    _showNotificationsInForeground = showNotificationsInForeground;
    _reminderIntervalDays = reminderIntervalDays;

    // Initialize local notifications plugin
    await _initializeLocalNotifications();

    // Set up FCM message handlers
    await _setupFCMHandlers();

    // Check for initial message (app opened from terminated state via notification)
    await _checkInitialMessage();

    _initialized = true;
    logi('NotificationService initialized successfully');
  } catch (e, stackTrace) {
    loge(e, 'Failed to initialize NotificationService', stackTrace);
    _onError?.call('Failed to initialize NotificationService: $e', stackTrace);
    rethrow;
  }
}