Hi, Community!
In the past few days i'm having troubles in undestanding how can i fetch data from Firebase to plot in a chart widget. I asked chatGPT to build a sample function, but the result put me in more doubts.
I know the data needs to be in a list format in order to be read by the chart, but... how?
The chatGPT sample code uses the "map" to return a list of 2 types. I've tried this in a custom function but doesnt worked.
Can someone help me understand how can i fetch data from Firebase to be proted in a chart widget? As a example, imagine that i need to build a bar chart that displays [X] the count of users (from Users collection) by the [Y] "created_date" field.
The chatGPT's sample code:
import 'package:cloud_firestore/cloud_firestore.dart';
Future<Map<DateTime, int>> getUserData() async {
Map<DateTime, int> userCountByDate = {};
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('users').get();
snapshot.docs.forEach((doc) {
DateTime createdTime = (doc['created_time'] as Timestamp).toDate();
DateTime dateOnly = DateTime(createdTime.year, createdTime.month, createdTime.day);
if (userCountByDate.containsKey(dateOnly)) {
userCountByDate[dateOnly] = userCountByDate[dateOnly]! + 1;
} else {
userCountByDate[dateOnly] = 1;
}
});
return userCountByDate;
}