observeFirestoreDocument method
Observes a Firestore document in real-time.
documentPath
: Path to the Firestore document.
Returns a ValueNotifier
that emits updates whenever the document changes.
Implementation
ValueNotifier<Map<String, dynamic>?> observeFirestoreDocument(String documentPath) {
final notifier = ValueNotifier<Map<String, dynamic>?>(null);
final docRef = _firestore.doc(documentPath);
final subscription = docRef.snapshots().listen((snapshot) {
if (!snapshot.exists) {
debugPrint('Document at $documentPath does not exist.');
SchedulerBinding.instance.addPostFrameCallback((_) {
notifier.value = null;
});
return;
}
final data = snapshot.data();
SchedulerBinding.instance.addPostFrameCallback((_) {
notifier.value = data;
});
}, onError: (error) {
debugPrint('Error observing Firestore document at $documentPath: $error');
SchedulerBinding.instance.addPostFrameCallback((_) {
notifier.value = null;
});
});
streams.add(subscription);
notifier.addListener(() {
if (!notifier.hasListeners) {
subscription.cancel();
debugPrint('Subscription canceled for $documentPath');
}
});
return notifier;
}