Ferda Nahit FIDANCI
Ferda Nahit FIDANCI

Reputation: 379

Why do i get null after using the foreach method in Flutter wih Firestore?

I was trying to get a user document and its sub-collection, simultaneously. But I found that it is not possible within a query. So I have decided to approach the problem from another perspective.


What do we have?

I have a getRelative() getter and it returns Stream<Relative>.

  Stream<Relative> get getRelative async* {
    List<Patient> patientList;

    patientList = await getPatientCollection
        .forEach((element) => element.patients)
        .then((value) => value);

      yield* usersCollection
          .document(_userEmail)
          .snapshots()
          .map((snapshot) => _relativeDataFromSnapshot(snapshot, patientList));
    
  }

getPatientCollection() is another getter method and it returns Stream<PatinetList>. I am not gonna give detail of the getter. Because it works fine.


What is the problem?

The problem is when I get Stream<PatientList>, I am getting a Stream. So, just to convert it to Future, I have used forEach method. And it also works fine. I can see element.patients is not empty. I can see inside of it and its return type List<Patient> as it should be.

But when I was debugging it, after forEach() has done its job, I have realized that it return null. And patientList become null. That causes a problem.


What am I asking?

  1. What does it cause this problem? And how can I solve it?
  2. Is there any better way to get subcollection without using another Stream to get patient subcollection (getPatientCollection)?

Upvotes: 2

Views: 496

Answers (1)

jamesdlin
jamesdlin

Reputation: 90105

Stream.forEach is the Stream equivalent of List.forEach (which returns void). It's for doing some operation on each element, not for returning a new collection. If you want to convert a Stream<T> to a List<T>, you can do await stream.toList().

Upvotes: 2

Related Questions