65 lines
1.8 KiB
Dart
65 lines
1.8 KiB
Dart
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<NotificationModel> _notifications = [];
|
|
List<NotificationModel> 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<DatabaseEvent>? 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<dynamic, dynamic>.from(event.snapshot.value as Map);
|
|
|
|
data.forEach((key, value) {
|
|
_notifications.add(
|
|
NotificationModel.fromMap(Map<dynamic, dynamic>.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();
|
|
}
|
|
}
|