Skip to content

Instantly share code, notes, and snippets.

@dayerdl
Last active July 24, 2023 14:53
Show Gist options
  • Save dayerdl/e36099c9bd82eead27250dfc8ea41f22 to your computer and use it in GitHub Desktop.
Save dayerdl/e36099c9bd82eead27250dfc8ea41f22 to your computer and use it in GitHub Desktop.
// Three different ways to access a document
//using a DocumentSnapshot - does not retrieve the document
Stream<WorkoutSession?> getWorkoutStream(String workoutId) {
return FirebaseFirestore.instance
.collection('users')
.doc('testuserId')
.collection('workouts')
.doc(workoutId)
.snapshots()
.map((DocumentSnapshot<Map<String, dynamic>> snapshot) {
if (snapshot.exists && snapshot.data() != null) {
// WorkoutSession.fromJson should be implemented in your WorkoutSession class
return WorkoutSession.fromJson(snapshot.data()!);
} else {
// If the document with the specified workoutId doesn't exist, return null
return null;
}
});
}
// Using a collection - it works offline
Stream<List<WorkoutSession>> getUsersWorkouts() {
final collectionRef = FirebaseFirestore.instance
.collection('users')
.doc('testuserId')
.collection('workouts');
return collectionRef.snapshots().map<List<WorkoutSession>>(
(QuerySnapshot<Map<String, dynamic>> snapshot) {
if (snapshot.docs.isNotEmpty) {
return snapshot.docs
.map<WorkoutSession>(
(doc) => WorkoutSession.fromJson(doc.data()),
)
.toList();
} else {
return [];
}
},
);
}
//Using GET - cant find the document, the error says "cloud_firestore/unavailable"
Future<WorkoutSession?> getWorkoutStream(String workoutId) async {
final docSnapshot = await FirebaseFirestore.instance
.collection('users')
.doc('testuserId')
.collection('workouts')
.doc(workoutId).get();
if(docSnapshot.exists) {
return WorkoutSession.fromJson(docSnapshot.data()!);
} else {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment