How to get a subcollection from a document firestore flutter

Viewed 77

Im trying to fetch the documents from a subcollection which is in another document, and when I try to fetch the docs and fill a local list with the "docs data" it doesn't fill it, can anyone tell me what I'm doing wrong here?

My method of when I try to fetch the subcollection:

  static Stream<List<CheckInOutModel>> employeeCheckInOutStream() {
    return firebaseFirestore
        .collection('employees')
        .doc(auth.currentUser!.uid)
        .collection('employeeList')
        .snapshots()
        .asyncMap((QuerySnapshot querySnapshot) {
      final List<CheckInOutModel> employeesCheckInOutList = [];
      for (final element in querySnapshot.docs) {
        firebaseFirestore
            .collection('employees')
            .doc(auth.currentUser!.uid)
            .collection('employeeList')
            .doc(element.id)
            .collection('checkInOutList')
            .snapshots()
            .asyncMap((QuerySnapshot query) {
          for (final element in query.docs) {
            final employeeCheckInOutModel =
                CheckInOutModel.fromDocumentSnapshot(
              documentSnapshot: element,
            );
            employeesCheckInOutList.add(employeeCheckInOutModel);
          }
        });
      }
      return employeesCheckInOutList;
    });
  }

My method when I fetch the fields of the documents that the subcollection is in:

  static Stream<List<EmployeeModel>> employeeStream() {
    return firebaseFirestore
        .collection('employees')
        .doc(auth.currentUser!.uid)
        .collection('employeeList')
        .snapshots()
        .map((QuerySnapshot query) {
      final List<EmployeeModel> employees = [];
      for (final employee in query.docs) {
        final employeeModel =
            EmployeeModel.fromDocumentSnapshot(documentSnapshot: employee);
        employees.add(employeeModel);
      }
      return employees;
    });
  }

enter image description here enter image description here

1 Answers

So I figured out what I did wrong here, I tried to call a stream of it when I only needed it when a callBack is called, so I changed the logic accordingly and went with Future instead Stream

My updated code:

  static Future<List<CheckInOutModel>> employeeCheckInOutStream({
    required String id,
  }) async {
    final List<CheckInOutModel> employeesCheckInOutList = [];
    final query = await firebaseFirestore
        .collection('employees')
        .doc(auth.currentUser!.uid)
        .collection('employeeList')
        .doc(id)
        .collection('checkInOutList')
        .get();

    for (final employee in query.docs) {
      final employeeCheckInOutModel = CheckInOutModel.fromDocumentSnapshot(
        documentSnapshot: employee,
      );
      employeesCheckInOutList.add(employeeCheckInOutModel);
    }

    return employeesCheckInOutList;
  }
Related