observeFirestoreValue<T> method

ValueNotifier<T?> observeFirestoreValue<T>(
  1. String documentPath,
  2. String fieldPath
)

Observes a specific field in a Firestore document in real-time.

  • documentPath: Path to the Firestore document.
  • fieldPath: Path to the nested field in the document.

Returns a ValueNotifier that emits updates whenever the field changes.

Implementation

ValueNotifier<T?> observeFirestoreValue<T>(String documentPath, String fieldPath) {
  final notifier = ValueNotifier<T?>(null);
  final docRef = _firestore.doc(documentPath);

  final subscription = docRef.snapshots().listen((snapshot) {
    if (!snapshot.exists) {
      debugPrint('Document at $documentPath does not exist.');
      notifier.value = null;
      return;
    }

    final data = snapshot.data();
    if (data == null) {
      debugPrint("No data found at path $documentPath");
      notifier.value = null;
      return;
    }

    final nestedField = getNestedField(data, fieldPath);
    if (nestedField is T) {
      notifier.value = nestedField;
    } else {
      debugPrint(
        'Type mismatch: Expected $T, but got ${nestedField.runtimeType} for field $fieldPath.',
      );
      notifier.value = null;
    }
  }, onError: (error) {
    debugPrint('Error observing Firestore value at $documentPath: $error');
    notifier.value = null;
  });

  streams.add(subscription);

  notifier.addListener(() {
    if (!notifier.hasListeners) {
      subscription.cancel();
      debugPrint('Subscription canceled for $documentPath');
    }
  });

  return notifier;
}