Trying to do the notification for all users.

This commit is contained in:
Van Leemput Dayron
2025-12-03 17:32:06 +01:00
parent fd19b88eef
commit a74d76b485
10 changed files with 505 additions and 227 deletions

View File

@@ -1,8 +1,16 @@
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:travel_mate/services/logger_service.dart';
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
LoggerService.info('Handling a background message: ${message.messageId}');
}
class NotificationService {
static final NotificationService _instance = NotificationService._internal();
factory NotificationService() => _instance;
@@ -41,8 +49,24 @@ class NotificationService {
// Handle foreground messages
FirebaseMessaging.onMessage.listen(_handleForegroundMessage);
// Handle token refresh
FirebaseMessaging.instance.onTokenRefresh.listen(_onTokenRefresh);
_isInitialized = true;
LoggerService.info('NotificationService initialized');
// Print current token for debugging
final token = await getFCMToken();
LoggerService.info('Current FCM Token: $token');
}
Future<void> _onTokenRefresh(String newToken) async {
LoggerService.info('FCM Token refreshed: $newToken');
// We need the user ID to save the token.
// Since this service is a singleton, we might not have direct access to the user ID here
// without injecting the repository or bloc.
// For now, we rely on the AuthBloc to update the token on login/start.
// Ideally, we should save it here if we have the user ID.
}
Future<void> _requestPermissions() async {
@@ -85,6 +109,20 @@ class NotificationService {
}
}
Future<void> saveTokenToFirestore(String userId) async {
try {
final token = await getFCMToken();
if (token != null) {
await FirebaseFirestore.instance.collection('users').doc(userId).set({
'fcmToken': token,
}, SetOptions(merge: true));
LoggerService.info('FCM Token saved to Firestore for user: $userId');
}
} catch (e) {
LoggerService.error('Error saving FCM token to Firestore: $e');
}
}
Future<void> _handleForegroundMessage(RemoteMessage message) async {
LoggerService.info('Got a message whilst in the foreground!');
LoggerService.info('Message data: ${message.data}');