it0/it0_app/lib/features/notifications/presentation/providers/notification_providers.dart

58 lines
1.7 KiB
Dart

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/config/app_config.dart';
import '../../../../core/services/notification_service.dart';
import '../../domain/entities/app_notification.dart';
/// Global local notifications plugin instance (initialized in main.dart).
final localNotificationsPluginProvider =
Provider<FlutterLocalNotificationsPlugin>((ref) {
return FlutterLocalNotificationsPlugin();
});
/// Notification service singleton.
final notificationServiceProvider = Provider<NotificationService>((ref) {
final config = ref.watch(appConfigProvider);
final plugin = ref.watch(localNotificationsPluginProvider);
return NotificationService(
baseUrl: config.apiBaseUrl,
localNotifications: plugin,
);
});
/// Accumulated notification list.
class NotificationListNotifier extends StateNotifier<List<AppNotification>> {
NotificationListNotifier() : super([]);
void add(AppNotification notification) {
state = [notification, ...state];
}
void markRead(String id) {
state = state.map((n) {
if (n.id == id) return n.copyWith(isRead: true);
return n;
}).toList();
}
void markAllRead() {
state = state.map((n) => n.copyWith(isRead: true)).toList();
}
void clear() {
state = [];
}
}
final notificationListProvider =
StateNotifierProvider<NotificationListNotifier, List<AppNotification>>(
(ref) {
return NotificationListNotifier();
});
/// Unread notification count.
final unreadNotificationCountProvider = Provider<int>((ref) {
final notifications = ref.watch(notificationListProvider);
return notifications.where((n) => !n.isRead).length;
});