From 9c4ad5cdb2360bd44a2d9849b43c54629a12c484 Mon Sep 17 00:00:00 2001 From: sBubshait Date: Thu, 17 Jul 2025 10:50:38 +0300 Subject: [PATCH] feat: request notifications access only AFTER user action --- lib/main.dart | 14 +++++++------ lib/services/notification_service.dart | 27 +++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index fe5f345..17baebf 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -6,12 +6,8 @@ import 'services/notification_service.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); - await Firebase.initializeApp( - options: DefaultFirebaseOptions.currentPlatform, - ); - - NotificationService().initialize(); - + await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); + runApp(MyApp()); } @@ -61,6 +57,9 @@ class _LandingPageState extends State _showBottomSheet = true; }); _animationController.forward(); + + // Request notification permissions on user action + NotificationService().requestPermissionAndSetup(); } void _hideBottomSheet() { @@ -78,6 +77,9 @@ class _LandingPageState extends State } void _navigateToHome() { + // Request notification permissions on user action + NotificationService().requestPermissionAndSetup(); + Navigator.of( context, ).push(MaterialPageRoute(builder: (context) => HomeScreen())); diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 4643dae..68efb4e 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -31,15 +31,36 @@ class NotificationService { } _messaging = FirebaseMessaging.instance; - - await _requestPermission(); - await _subscribeToTopics(); await _setupMessageHandlers(); } catch (e) { print('Error initializing notifications: $e'); } } + Future requestPermissionAndSetup() async { + try { + if (!kIsWeb) { + print('Notifications are only supported on web platform'); + return; + } + + if (!_isNotificationSupported()) { + print('Notifications are not supported in this browser'); + return; + } + + if (_messaging == null) { + _messaging = FirebaseMessaging.instance; + await _setupMessageHandlers(); + } + + await _requestPermission(); + await _subscribeToTopics(); + } catch (e) { + print('Error requesting notification permission: $e'); + } + } + bool _isNotificationSupported() { if (!kIsWeb) return false;