Yashank
Yashank

Reputation: 813

How may I query 2 documents in Flutter Firestore and return as a List?

New to the world of Flutter and Dart.

I'm trying to Query from one collection (Sessions), with another collection of User, where each session can have only one user. I want to get each Session, add User Data and return to my Future<List < Sessions > >.

I have Models for both Sessions and the User, and I'm able to extract both the Sessions document and then being able to form my Sessions using the User info, however I have no luck in returning the correct data. It seems like im getting the query fine, however my returning data is coming out as a List< Future < Sessions > > instead of a List< Sessions >.

Sessions Model

 Sessions(
      {this.id,
      this.title,
      this.datetime,
      this.userName,
      this.userImage});

  factory Sessions.fromJson(DocumentSnapshot doc, userName, userImage) {
    String id = doc.documentID;
    Map json = doc.data;
    return Sessions(
      id: id,
      title: json['title'],
      datetime: json['datetime'].toDate(),
      userName: userName,
      userImage: userImage,
    );
  }

Firebase Query

Future<List<Sessions>> getSessions() async {
    // Getting Sessions
    final result = await _liveSessionsRef
        .where('isFeatured', isEqualTo: true)
        .getDocuments();

    // Querying from Users and returning Sessions with User Id and User Image
    final data = result.documents.map((doc) async {
      return await _userCollectionRef
          .document(doc.data['id'])
          .get()
          .then(
        (value) {
          return Sessions.fromJson(doc, value.data['name'], value.data['image']);
        },
      );
    }).toList();
  }
return data;
}

Upvotes: 0

Views: 449

Answers (1)

thien nguyen
thien nguyen

Reputation: 326

Future<List<Sessions>> getSessions() async {
    // Getting Sessions
    final result = await _liveSessionsRef
        .where('isFeatured', isEqualTo: true)
        .getDocuments();

    // Querying from Users and returning Sessions with User Id and User Image
    final data = Future.wait(result.documents.map((doc) {
      return _userCollectionRef
          .document(doc.data['id'])
          .get()
          .then(
        (value) {
          return Sessions.fromJson(doc, value.data['name'], value.data['image']);
        },
      );
    }).toList());
  }
return data;
}

Upvotes: 2

Related Questions