QasimSiddiqui
QasimSiddiqui

Reputation: 100

How to get documents from different collections in firebase and add them to a single List to return as Stream?

I am trying to create an Attendance App, so I want to get the courses in which the students are registered. The Student's class looks something like this:

class Student {
  final String name;
  final String email;
  final String number;
  final String regNo;
  List<CourseIDAndInstructorID> courses;

  Student({this.name, this.email, this.number, this.regNo});
}

The List named courses contains the document-ID of the instructor whose course it is, and the document-ID of the course document.(As one student would obviously be taking classes from different instructors)

Now using these two fields, I want to get the documents of the courses, create an Object of the custom class Course and then add this object to a List, that would be returned so that it can be displayed on the GUI.

But I am getting this Exception, whereas I clearly have data in the object.

The image of the Exception Message can be seen here

final CollectionReference _instructorCollection =
    Firestore.instance.collection('instructors');

final CollectionReference _studentCollection =
    Firestore.instance.collection('students');

Stream<List<Course>> _getStudentCourses() async* {
    List<Course> courseList;

    DocumentSnapshot stdDoc = await _studentCollection.document(uid).get();
    Student _student = new Student.fromSnapshot(stdDoc);

    if (_student.courses.length == 0) {
      return; //TODO add appropriate return type
    } else {
      int len = _student.courses.length;
      while (len != 0) {
        len--;
        DocumentSnapshot snapshot = await _instructorCollection
            .document(_student.courses[len].instructorUID)
            .collection('courses')
            .document(_student.courses[len].courseID)
            .get();
        print(snapshot.data);
        Course course = new Course.fromSnapshot(snapshot);
        courseList.add(course);
        yield courseList;
      }
    }
  }

Can someone tell me, what I'm doing wrong or how I can do this? If something is missing from the context of the question, kindly tell me so that I can add that.

Upvotes: 1

Views: 198

Answers (1)

Juancki
Juancki

Reputation: 1872

You may need to create the List object instead of just a pointer.

List<Course> courseList = new List();

source

Upvotes: 1

Related Questions