Flutter: Get data from two collections in Firebase

Viewed 1662

I am trying to display a ListView with the events that I have in a firebase collection and in which there is a reference to another collection but I cannot get it to return the information in full. Is there a way to reference that second collection and return the full data?

Places Events

I've tried doing it this way but it doesn't work

class Event {
  String id;
  Timestamp date;
  String description;
  String name;
  String place;
  Place placeData;

  Event(this.id, this.date, this.description, this.name, this.place);
  Event.withPlace(this.id, this.date, this.description, this.name, this.place, this.placeData);

  Event.fromFirestore(DocumentSnapshot doc)
      : id= doc.documentID,
        date = doc.data['date'] ?? '',
        description = doc.data['description'] ?? '',
        name = doc.data['name'] ?? '',
        place = doc.data['place'] ?? '';
}

Stream<List<Event>> getFutureEventsFromFirestore() {
  return Firestore.instance.collection('events').orderBy('date', descending: false).snapshots().map(futureEventListWithPlace);
}

List<Event> futureEventList(QuerySnapshot query) {
  return query.documents.where((event) => event['date'].toDate().isAfter(DateTime.now())).map((event) => Event.fromFirestore(event)).toList();
}

List<Event> futureEventListWithPlace(QuerySnapshot query) {
  return query.documents.where((event) => event['date'].toDate().isAfter(DateTime.now())).map((event) {
    final Event eventF = Event.fromFirestore(event);
    FirebaseProvider.getPlaceFromFirestore(eventF).then((value){
      Event.withPlace(eventF.id, eventF.date, eventF.description, eventF.name, eventF.place, value);
    });
  }).toList();
}

Future<Place> getPlaceFromFirestore(Event event) async {
  DocumentReference documentReference = Firestore.instance.collection("places").document(event.place);
  await documentReference.get().then((DocumentSnapshot ds) {
    return Place.fromMap(ds.data);
  });
}

List<Event> pastEventList(QuerySnapshot query) {
  return query.documents.where((event) => event['date'].toDate().isBefore(DateTime.now())).map((event) => Event.fromFirestore(event)).toList();
}
2 Answers

It looks like you are not using a field of type 'reference' for your place field in the 'events' document. So, ensure this field is set to 'reference' and that it contains a valid value.

The correct value for that field should be the full document path.

Which, in your case would be:

places/socialClub

You should then be able to access the place snapshot from the event object as follows:

data['place'].get();

For more info : https://firebase.google.com/docs/reference/js/firebase.database.Reference

Related