How to print values from array field from Firestore?

Viewed 45

I have the following courses array in Firestore:

enter image description here

How can I print all the items in Courses array?

I have the following code which currently just fetches the data from Firestore:

printAllValuesFromArray() {
    var courses = FirebaseFirestore.instance
        .collection('CurrentCourses')
        .doc(user.uid)
        .get()
        .then((value) {
      return value['courses'];
    });
}
3 Answers
value['courses'].forEach((val) {
print(val);
});

// Can you try this

You can try this,

printallvaluesfromarray() {

    var courses = FirebaseFirestore.instance
        .collection('CurrentCourses')
        .doc(user.uid)
        .get()
        .then((value) {
        print(value.toString())
      return value['courses'];
    });
  }

You are correctly fetching the document of the user, all you need is to just print the value like the following:

Future<void> printAllValuesFromArray() {
  return FirebaseFirestore.instance
      .collection('CurrentCourses')
      .doc(user.uid)
      .get()
      .then((document) {
    final courses = document['Courses'];
    for (var course in courses) {
      print(course);
    }
  });
}

Note: You were using incorrect key to access the courses from the document which was courses while the correct one is Courses with capital C,

Related