import 'dart:async'; import 'package:flutter/material.dart'; import 'package:firebase_database/firebase_database.dart'; import '../models/notification_model.dart'; import '../services/firebase_service.dart'; import '../services/notification_service.dart'; class NotificationProvider extends ChangeNotifier { List _notifications = []; List get notifications => _notifications; /// Track how many notifications existed on the previous update so we can /// detect newly added entries and fire an OS push for them. int _previousCount = 0; StreamSubscription? subscription; void startListening() { subscription?.cancel(); subscription = FirebaseService.notificationRef.onValue.listen((event) { final prev = _previousCount; _notifications = []; if (event.snapshot.value == null) { _previousCount = 0; notifyListeners(); return; } final data = Map.from(event.snapshot.value as Map); data.forEach((key, value) { _notifications.add( NotificationModel.fromMap(Map.from(value)), ); }); _notifications = _notifications.reversed.toList(); _previousCount = _notifications.length; // If new entries appeared, fire an OS notification for the latest one if (_notifications.isNotEmpty && _notifications.length > prev) { final latest = _notifications.first; NotificationService.showNotification( title: latest.title, body: latest.message, id: DateTime.now().millisecondsSinceEpoch ~/ 1000, ); } notifyListeners(); }); } @override void dispose() { subscription?.cancel(); super.dispose(); } }