1

In my app, the user will fill out a form, and then Firebase will send them a random Document after 10 minutes. I am not entirely sure how to do this and was wondering if someone could point me in the right direction.

Thank you for your kind support

  • Instead of the code here is probably more handy to understand why and how to get random data out of firebase answered directly from a Firebase team member: https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection – Stefano Saitta Apr 07 '20 at 21:58
  • Actually I saw this inquiry but it is really difficult for me to implement to the flutter. This is the problem. –  Apr 08 '20 at 06:46
  • Ok i see, i'll try to port the code in that question to Dart for you :) – Stefano Saitta Apr 08 '20 at 08:46
  • Grazie Mille! :) –  Apr 08 '20 at 08:47

1 Answers1

0

Unfortunately, there is no super simple way to do this. The best way to do this would be to pull all the documents from your collection, shuffle them, then retrieve the first document. Example code:

//get firestore documents from collection
QuerySnapshot qs = await Firestore.instance.collection('myCollection').getDocuments();
List<DocumentSnapshot> listedQS = qs.documents; //listed documents
var random = new Random(); //dart math
//shuffle the array
for (var i = listedQS.length - 1; i > 0; i--) {
  var n = random.nextInt(i + 1);
  var temp = listedQS[i];
  listedQS[i] = listedQS[n];
  listedQS[n] = temp;
}
DocumentSnapshot randomDocument = listedQS[0]; //the random data from firebase
asterisk12
  • 394
  • 2
  • 9
  • Thanks for your kind support! I will try your code. Additionally how can I retrieve and post the data after 10 minutes of the request of the unique user? –  Apr 08 '20 at 06:48
  • I hope my code helped, if it did, please mark it as the answer for others who might have the same problem as you! In terms of the follow up question, I'm a little unsure about the question. For doing something 10 minutes in the future, you're going to want to check out the Timer() functionality in dart. As far as retrieving and posting data, that will all be Firestore commands :) – asterisk12 Apr 08 '20 at 18:59
  • Thanks your kind support. I will try your code within today and inform you –  Apr 09 '20 at 08:34
  • How I can show only 1 item in listviewer because it shows all the data randomly... –  Apr 10 '20 at 14:05
  • You want to make the length equal to 1, and you want to pass in the shuffled list :) – asterisk12 Apr 10 '20 at 14:25
  • I would like to show only one data from firebase but when I retrieve the data from database it is not going to shoe same data. I mean if ı have 100 docs in the database ıt will show 1 item to user but it is not going to show same item when user request –  Apr 10 '20 at 14:31