Harsh Patel
Harsh Patel

Reputation: 269

How to merge results of two Future<QuerySnapshots> into one one Future<QuerySnapshots> in flutter using firebase, using Future Builder

So basically I want to add results of two queries into one query(removing duplicates) and than display. How can I do it?

Future<QuerySnapshot> allUsersProfile = usersReference.where("searchName", isGreaterThanOrEqualTo: str.toLowerCase().replaceAll(' ', '')).limit(5).get();
Future<QuerySnapshot> allSameUsersProfile = usersReference.where("searchName", isEqualTo: str.toLowerCase().replaceAll(' ', '')).limit(5).get();

Future<QuerySnapshot> futureSearchResults;

displayUsersFoundScreen(){
return FutureBuilder(
  future: futureSearchResults,
  builder: (context, dataSnapshot){

I want to store results of both into futureSearchResults only, as I use Future Builder to display the results.

Can any body can help me? Thanks in advance.

Upvotes: 2

Views: 1358

Answers (1)

glavigno
glavigno

Reputation: 503

It is possible to use the Future.wait method in this case. The builder callback will await for all futures to resolve and the result in a List.

FutureBuilder(
    future: Future.wait([
         allUsersProfile(), 
         allSameUsersProfile(),
    ]),
    builder: (
       context,
       AsyncSnapshot<List<QuerySnapshot>> snapshot, 
    ){
         // ...
    }
);


Other option if you want to merge documents property is to implement a futureSearchResults function that will call futures and apply transformation.

Future<QuerySnapshot> futureSearchResults() async {
  final future1 = await allUsersProfile();
  final future2 = await allSameUsersProfile();
  
  future1.data.documents.add(future2.data.documents);
  
  return future1;
}

Upvotes: 1

Related Questions