Reputation: 27
I wanna get the previous day and today's record please help me out thanks I am storing date like this.
static final DateTime todaysDate = DateTime.now();
static final DateTime yesterdayDate =
DateTime.utc(todaysDate.year, todaysDate.month, todaysDate.day - 1);
final String formatte = formatter.format(yesterdayDate);
**Here is my controller to get data from the firebase.**
final controller = ScreenshotController();
final Stream<QuerySnapshot> otherStream =
FirebaseFirestore.instance.collection('lott').snapshots();
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: otherStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
print('Something went Wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final List storedocs = [];
snapshot.data!.docs.map((DocumentSnapshot document) {
Map a = document.data() as Map<String, dynamic>;
storedocs.add(a);
a['id'] = document.id;
}).toList();
Any example would be great and If you can also highlight how to get specific results would also be great.
Upvotes: 0
Views: 2604
Reputation: 1741
You should add an extra field called createdAt
in your documents and store the creation date of this document in it.
ex:
'createdAt': FieldValue.serverTimestamp(),
Then you can simply query Firestore like this
Future<QuerySnapshot<Map<String, dynamic>>> getRecentDocs() async {
final Timestamp now = Timestamp.fromDate(DateTime.now());
final Timestamp yesterday = Timestamp.fromDate(
DateTime.now().subtract(const Duration(days: 1)),
);
final query = FirebaseFirestore.instance
.collection('collectionPath')
.where('createdAt', isLessThan: now, isGreaterThan: yesterday);
return query.get();
}
Read more about Firestore queries and limitations here https://firebase.google.com/docs/firestore/query-data/queries
Upvotes: 3