Mark Nugromentry
Mark Nugromentry

Reputation: 304

how to perform query to Firestore and order result Randomly in Flutter

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)

Upvotes: 0

Views: 81

Answers (1)

Karolina Hagegård
Karolina Hagegård

Reputation: 1387

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];
              },
            );
          }
        },
      ),
    );
  }
}

Upvotes: 2

Related Questions