Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save keiwanmosaddegh/575e9b9a33ff32038df3d9a3cdc3e899 to your computer and use it in GitHub Desktop.

Select an option

Save keiwanmosaddegh/575e9b9a33ff32038df3d9a3cdc3e899 to your computer and use it in GitHub Desktop.
/*
This implementation is based on the Auto-ID approach from the following source:
https://stackoverflow.com/a/46801925
*/
static Future<Object> getRandomDocument(String collectionId) async {
final randomId =
FirebaseFirestore.instance.collection(collectionId).doc().id;
final documentSnapshot = await () async {
return FirebaseFirestore.instance
.collection(collectionId)
.where(FieldPath.documentId, isGreaterThanOrEqualTo: randomId)
.limit(1)
.get()
.then(
(snapshot) async => snapshot.docs.isNotEmpty
? snapshot
: await FirebaseFirestore.instance
.collection(collectionId)
.where(FieldPath.documentId, isLessThanOrEqualTo: randomId)
.limit(1)
.get(),
)
.then(
(snapshot) => snapshot.docs.isNotEmpty ? snapshot.docs.first : null,
);
}();
final data = documentSnapshot?.data();
if (data == null) {
throw const FormatException("Random document could not be selected.");
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment