Amol Jandial
Amol Jandial

Reputation: 49

How do i retrieve a List<Map<String,Object>> from cloud firestore and convert it into a custom model?

The structure of my data looks like this: enter image description here

I want to retrieve this data which I have done using this where studentReference is CollectionReference to students collection. enter image description here

This returns me this enter image description here

Now I want to map this data into a Custom Subject class that looks like this

class Subjects {
  int totalAttended;
  int attended;
  int missed;
  final String subjectName;
  final String subjectId;
  final String subjectTeacher;

  Subjects(
      {this.attended,
      this.missed,
      this.totalAttended = 0,
      this.subjectId,
      this.subjectName,
      this.subjectTeacher});
}

But can't figure out how to do this mapping. I know I need to use stream but don't know how.

Any help would be immensely appreciated.

Upvotes: 0

Views: 224

Answers (1)

Loren.A
Loren.A

Reputation: 5575

Going forward try not to use screenshots when sharing code. Firebase collection is one thing, but your retreiveData and the print statement could have easily been embedded code in the post. If somebody wants to help and needs to paste your code into their IDE they're definitely not gonna want to type it out manually.

Anyway, this should get you most of the way there. It should give you the idea at least. By looking at your collection, Subjects is a list consisting of 2 maps. So here's a function that iterates through the list, pulls out the key/value pairs from the maps, creates a Subjects object out of the values, adds the Subjects objects to a list, then returns the list.

List<Subjects> getSubjects(List subjectList) {
  final List<Subjects> list = [];

  for (int i = 0; i < subjectList.length; i++) {
    final map = subjectList[i];
    final totalAttended = map['totalAttended'];
    final attended = map['attended'];
    final missed = map['missed'];
    final subjectName = map['subjectName'];
    final subjectId = map['subjectId'];
    final subjectTeacher = map['subjectTeacher'];

    final subject = Subjects(
        totalAttended: totalAttended,
        attended: attended,
        missed: missed,
        subjectName: subjectName,
        subjectTeacher: subjectTeacher,
        subjectId: subjectId);

    list.add(subject);
  }
  return list;
}

You can declare a subjectList outside of the retreiveData function, then where you currently have your print statement, you could do this

subjectList = getSubjects(value.data()['subjects']);

Then you have a list of Subjects objects that you can use as you need to.

Upvotes: 1

Related Questions