initialize method

Future<void> initialize({
  1. dynamic onNotificationTapped(
    1. NotificationResponse
    )?,
})

Initialize the engagement tracking service

onNotificationTapped optional callback that will be invoked when user taps a notification. The callback receives a NotificationResponse object containing all notification data.

Navigation Behavior:

  • If onNotificationTapped is provided: SDK skips automatic navigation, you handle it in the callback
  • If onNotificationTapped is null: SDK handles navigation automatically based on payload

Engagement tracking always happens regardless of callback presence.

Implementation

Future<void> initialize({
  Function(NotificationResponse)? onNotificationTapped,
}) async {
  _userNotificationCallback = onNotificationTapped;
  if (_initialized) {
    debugPrint('EngagementTrackingService already initialized, skipping');
    return;
  }

  await _loadPendingEvents();
  _startBatchTimer();

  /// Parse payload string to Map
  Map<String, dynamic> _parsePayload(String payload) {
    if (payload.isEmpty) return {};

    final Map<String, dynamic> data = {};
    final parts = payload.split('&');
    for (final part in parts) {
      final keyValue = part.split('=');
      if (keyValue.length == 2) {
        data[Uri.decodeComponent(keyValue[0])] =
            Uri.decodeComponent(keyValue[1]);
      }
    }
    return data;
  }

  await NotificationDisplayService.instance.initialize(
    onNotificationTapped: (response) async {
      debugPrint('=== ENGAGEMENT: Notification tapped ===');
      debugPrint('Notification response: ${response.payload}');

      // Parse data from payload
      final data = _parsePayload(response.payload ?? '');

      // Track engagement when user taps notification
      await _trackEngagementFromData(data);

      // Handle navigation based on callback presence
      if (onNotificationTapped != null) {
        // User provided callback - let them handle navigation
        debugPrint(
            '=== Invoking user notification callback (user handles navigation) ===');
        onNotificationTapped(response);
      } else {
        // No user callback - SDK handles navigation automatically
        debugPrint('=== SDK handling navigation automatically ===');
        await _navigationService.handleNotificationNavigation(data);
      }
    },
  );
  // Register background message handler for data-only messages
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  _setupNotificationHandlers();

  _initialized = true;
  debugPrint('EngagementTrackingService initialized');
}