Get Firestore documents reference field's data using withConverter in flutter

Viewed 788

I've Appointments collections with student and teacher as reference type along with other fields.

I want to get the list of Appointments using CollectionReference.withConverter. But because of reference fields, I'm not able to fetch them.

Example code:

FirebaseFirestore.instance.collection('appts').withConverter<Appointment>(
      fromFirestore: (snapshot, _) {
        Map<String, dynamic> appt = snapshot.data()!;

        Student student = await appt['student'] // <---- Error as await is NOT allowed here
                .get()
                .then((studentSnapshot) => Student.fromMap(studentSnapshot.data()!));

        return Appointment.fromMap(
          snapshot.data()!
            ..['id'] = snapshot.id
            ..['student'] = student,
        );
      },
      toFirestore: (appointment, _) => ...,
    );

await is not allowed as withConverter<Appointment> expects fromFirestore to return Appointment object instead of Future<Appointment>

Without await, I'll get Future<Student>, and not sure how to map the complete document to Student type.

Is there anyway Flutter's Firestore auto-fetches the reference documents instead of I fetching them manually?

1 Answers

Here are some examples that could help you with their documentation.

Using withCoverter in flutter withConverter Now, you can make use of withConverter in various places in order to change this type:

DocumentReference.withConverter:
final modelRef = FirebaseFirestore
    .instance 
    .collection('models') 
    .doc('123') 
    .withConverter<Model>( 
        fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!), 
        toFirestore: (model, _) => model.toJson(), 
);

DocumentReference.withConverter (Public Documentation)

CollectionReference.withConverter:

final modelsRef = FirebaseFirestore
      .instance
      .collection('models')
      .withConverter<Model>( fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!), 
      toFirestore: (model, _) => model.toJson(), 
);

CollectionRefence.withConverter (Public Documentation)

Query.withConverter:

final personsRef = FirebaseFirestore
      .instance 
      .collection('persons') 
      .where('age', isGreaterThan: 0) 
      .withConverter<Person>( fromFirestore: (snapshot, _) => Person.fromJson(snapshot.data()!), 
      toFirestore: (model, _) => model.toJson(), 
);

Query.withCoverter (Public Documentation)

Here is also some documentation of firebase, flutter:

https://firebase.flutter.dev/docs/firestore/usage/ https://firebase.google.com/docs/reference/js/v8/firebase.firestore.CollectionReference

Related