👁️‍🗨️ Relational Data Fetching

Fetch data associated to the current user

Relational Data Fetching

The pattern below is useful for listening to a realtime stream that depends on the current user’s UID. The switchmap extension method from RxDart is an essential tool for combining two streams.

file_type_flutter firestore.dart
class FirestoreService {
  /// Listens to current user's report document in Firestore
  Stream<Report> streamReport() {
    return AuthService().userStream.switchMap((user) {
      if (user != null) {
        var ref = _db.collection('reports').doc(user.uid);
        return ref.snapshots().map((doc) => Report.fromJson(doc.data()!));
      } else {
        return Stream.fromIterable([Report()]);
      }
    });
  }
}

Questions? Let's chat

Open Discord