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

567

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;
}

Share:
567
Harsh Patel
Author by

Harsh Patel

Updated on December 28, 2022

Comments

  • Harsh Patel
    Harsh Patel over 1 year

    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.

  • Harsh Patel
    Harsh Patel about 3 years
    in this I can't use dataSnapshot.data.documents.forEach((document). It is giving error that document isn't defined for the type 'List<QuerySnapshot>'
  • glavigno
    glavigno about 3 years
    please check my edited answer, i added an option to merge documents property.