Home > Back-end >  Flutter firebase firestore combine 2 query
Flutter firebase firestore combine 2 query

Time:03-06

In the example below, I want to combine 2 firestore queries, but I could not get it to work.

final List<Who> pagedData =
        await _query.get().then((QuerySnapshot snapshot) async {
      if (snapshot.docs.isNotEmpty) {
        _lastDocument = snapshot.docs.last;
      } else {
        _lastDocument = null;
      }
      return snapshot.docs.map((QueryDocumentSnapshot e) async {
        final data = e.data() as Map<String, dynamic>;
        Whoes w = Whoes.fromMap(e.data());
        User u = await _firestore
            .collection("user")
            .doc(data['s'])
            .get()
            .then((DocumentSnapshot documentSnapshot) => User.fromMap(
                documentSnapshot.data()));
        return Who(w, u);
      }).toList();
    });

When I put await in the user part, things get confused and I couldn't edit it.

What I want to output as a result is List<Who>

What am I missing?

It gives me this error:

The return type 'List<Future<Who>>' isn't a 'Future<List<Who>>', as required by the closure's context.

CodePudding user response:

I solved the problem, I leave it here for anyone who encounters this

final List<Who> pagedData =
        await _query.get().then((QuerySnapshot snapshot) async {
      if (snapshot.docs.isNotEmpty) {
        _lastDocument = snapshot.docs.last;
      } else {
        _lastDocument = null;
      }
      Iterable<Future<Who>> futureWho = 
      snapshot.docs.map((QueryDocumentSnapshot e) async {
        final data = e.data() as Map<String, dynamic>;
        Whoes w = Whoes.fromMap(e.data());
        User u = await _firestore
            .collection("user")
            .doc(data['s'])
            .get()
            .then((DocumentSnapshot documentSnapshot) => User.fromMap(
                documentSnapshot.data()));
        return Who(w, u);
      });
      Future<List<Who>> listWho = Future.wait(futureWho);
      return listWho;
    });
  • Related