Issue
I’m new in flutter firebase, how can i display the length of my Total sales sales record. I have the collection of SalesRecord and and a field name Created and i want to know how many sales i made during this Day.
My Code:
var todaySales = 0;
FutureBuilder(
future: FirebaseFirestore.instance
.collection('SalesRecord')
// .orderBy('Created', descending: true | false)
.where("Created", isGreaterThan: DateTime.now())
.get()
.then((myDocuments) {
setState(() {
todaySales = myDocuments.docs.length;
});
//print("${myDocuments.docs.length}");
}),
builder: (context, snapshot) {
if (snapshot.hasData) {
return const Center(
child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return const Center(
child: CircularProgressIndicator());
}
return Text(
todaySales.toString(),
style: const TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.bold,
),
);
}),
Code Update :-
FutureBuilder<QuerySnapshot<Map<String, dynamic>>>(
future: FirebaseFirestore.instance
.collection('SalesRecord')
.where("Created",
isGreaterThan: DateTime.now())
.get(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
snapshot.data!.docs.length.toString(),
style: const TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.bold,
),
);
} else if (snapshot.hasError) {
return const Center(
child: CircularProgressIndicator());
} else {
return CircularProgressIndicator();
}
}),
When i update the SalesRecord it change the value for a while but the record count back to 0 again by itself after 20sec
Solution
The reason for count getting back to 0 is that DateTime.now() gets the current date time i.e. if you made a sale 30 seconds ago it won’t be shown as the current time is 30 seconds greater than previous one.
So declare a variable as shown below which will get us the today’s date (2022-01-31 00:00:00.000) and zero time values to mark the beginning of the day.
DateTime dateToday = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);
And now use this in your code as:-
FutureBuilder<QuerySnapshot<Map<String, dynamic>>>(
future: FirebaseFirestore.instance
.collection('SalesRecord')
.where("Created",
isGreaterThan: dateToday)
.get(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
snapshot.data!.docs.length.toString(),
style: const TextStyle(
fontSize: 50.0,
fontWeight: FontWeight.bold,
),
);
} else if (snapshot.hasError) {
return const Center(
child: CircularProgressIndicator());
} else {
return CircularProgressIndicator();
}
})
Answered By – Deepak Lohmod
Answer Checked By – Marilyn (FlutterFixes Volunteer)