Last active
July 24, 2023 14:53
-
-
Save dayerdl/e36099c9bd82eead27250dfc8ea41f22 to your computer and use it in GitHub Desktop.
This file contains 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
// 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