Getting a single document out of Firestore in Flutter using a StreamProvider

Viewed 536

I've followed various guides to successfully get data out of a Firestore collection with a StreamProvider. What I can't quite seem to figure out is how to get a singular document and its associated fields.

For example, let's say I have a collection 'WeatherObs' with a document called '5-13-21' as shown below:

enter image description here

If I wanted to pull in the whole collection with my StreamProvider, I could easily just put it into a list like so:

class FirestoreService {

  FirebaseFirestore _db = FirebaseFirestore.instance;
  var random = Random();

  Stream<List<Weather>> getWeather() {

   return _db.collection('TodaysWeather').snapshots().map((snapshot) => snapshot.docs.map((event) => Weather.fromJson(event.data())).toList());

  }

I can't for the life of me, however, figure out how if I wanted to just access a single document the same way. I am able to get the document accessible in a key, value pair so I can use fromJson. But when I access the Provider object that calls the method in another class, it always returns null.

Stream<Weather> getWeather() {    

    return _db.collection('TodaysWeather').doc('5-13-21').snapshots().map((event) => FastFoodHealthEUser.fromJson(event.data()));      
   

  }

In the last example, I am not returning a list, but I don't think a list is necessary as I should be able to access the weather object and get access to its attributes like high (type String). Is accessing a single document in the same manner possible?

1 Answers

You can use where for checking on unique field on your documents like this code

Stream<List<VehicleCommentSessionModel>> getSomeoneCommentsList(
   {@required String sellerId}) {
  return _fbd
     .collection('comments')
    .where('sellerId', isEqualTo: sellerId)
    .snapshots()
    .map((qSnap) => qSnap.docs
        .map((doc) => VehicleCommentSessionModel.fromJson(doc.data()))
        .toList());
}
Related