0

I am retrieving specific documents from firestore collection using flutter stream builder.

the issue is I would like to display the results every single time in a different order (Randomely).

the stream is the below:

 stream: FirebaseFirestore.instance
  .collection('BusinessProfilesCollection')
  .where('Profile_direct_category',
      isEqualTo: selecteddirectcategory)
  .where('Profile_status', isEqualTo: "Active")
  .where('Profile_visibility', isEqualTo: "Yes")
  .where('Profile_city',
      isEqualTo: globaluserdefaultcity)
  .where('Profile_pinning_status',
      isEqualTo: "No")
  .snapshots(),

the problem is everytime the user do the query the data is returned in the same order. I would like to shuffle it somehow so I remove any advantage from any profile. (document)

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Mark Nugromentry
  • 195
  • 2
  • 10
  • There is no operator to randomize the order. The closest is what Dan explains in this highly upvoted answer: https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection – Frank van Puffelen Aug 29 '22 at 15:55
  • Hi Frank, I think this is about selecting random docs. while in my case it is not about the document selection, it should be the same everytime. it is about ordering these selected documents. in Orderby not Where. will review the full thread indeed. thanks – Mark Nugromentry Aug 29 '22 at 15:58
  • 1
    There is no operator to randomize the order on retrieval from the database. You will hav to shuffle them in your applicaiton code. – Frank van Puffelen Aug 29 '22 at 17:35

1 Answers1

2

I assume you have a list somewhere, where you display your documents? If so, you can use the .shuffle() operator on it! Example:

import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

String selecteddirectcategory = 'selecteddirectcategory';
String globaluserdefaultcity = 'globaluserdefaultcity';

class RandomResultsScreen extends StatefulWidget {
  @override
  _RandomResultsScreenState createState() {
    return _RandomResultsScreenState();
  }
}

class _RandomResultsScreenState extends State<RandomResultsScreen> {
  Stream<QuerySnapshot> myStream = FirebaseFirestore.instance
      .collection('BusinessProfilesCollection')
      .where('Profile_direct_category', isEqualTo: selecteddirectcategory)
      .where('Profile_status', isEqualTo: "Active")
      .where('Profile_visibility', isEqualTo: "Yes")
      .where('Profile_city', isEqualTo: globaluserdefaultcity)
      .where('Profile_pinning_status', isEqualTo: "No")
      .snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<QuerySnapshot>(
        stream: myStream,
        builder: (context, asyncSnapshot) {
          List<Widget> docs = [];
          QuerySnapshot? foundResults = asyncSnapshot.data;

          if (foundResults == null) {
            //It always wants to be null at first, and then you get errors for calling on null.
            return Center(child: CircularProgressIndicator());
          } else {
            for (QueryDocumentSnapshot doc in foundResults.docs) {
              Map<String, dynamic> docData = doc.data() as Map<String, dynamic>;
              docs.add(
                  MyWidget(docData) // Some Widget that you use to display your data
              );
            }
            docs.shuffle();  // <- Where the magic randomization happens!
            return ListView.builder(
              itemCount: docs.length,
              itemBuilder: (context, index) {
                return docs[index];
              },
            );
          }
        },
      ),
    );
  }
}
Karolina Hagegård
  • 1,180
  • 5
  • 26