initialize method
Initialize the notification display service
onNotificationTapped callback will be called when user taps notification
with the notification data payload
Implementation
Future<void> initialize({
Function(NotificationResponse)? onNotificationTapped,
}) async {
if (_initialized) return;
_onNotificationTapped = onNotificationTapped;
// Android initialization settings
const AndroidInitializationSettings androidSettings =
AndroidInitializationSettings('@mipmap/ic_launcher');
// iOS initialization settings
const DarwinInitializationSettings iosSettings =
DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
const InitializationSettings initSettings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
await _notificationsPlugin.initialize(
initSettings,
onDidReceiveNotificationResponse: _onNotificationResponse,
);
// Check if app was launched from a notification tap
final NotificationAppLaunchDetails? launchDetails =
await _notificationsPlugin.getNotificationAppLaunchDetails();
if (launchDetails != null &&
launchDetails.didNotificationLaunchApp &&
launchDetails.notificationResponse != null) {
debugPrint('=== APP LAUNCHED FROM NOTIFICATION ===');
debugPrint('Launch payload: ${launchDetails.notificationResponse!.payload}');
// Wait for the first frame to be rendered before attempting navigation
// This ensures the widget tree and navigation context are fully ready
SchedulerBinding.instance.addPostFrameCallback((_) {
debugPrint('=== HANDLING COLD START NOTIFICATION AFTER FIRST FRAME ===');
_onNotificationResponse(launchDetails.notificationResponse!);
});
}
// Request permissions for iOS
if (Platform.isIOS) {
await _notificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
// Create notification channel for Android
await _createNotificationChannel();
_initialized = true;
debugPrint('NotificationDisplayService initialized');
}