Created
May 14, 2024 07:06
-
-
Save keiwanmosaddegh/575e9b9a33ff32038df3d9a3cdc3e899 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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