I'm trying to create an app where there is a button, and when a user clicks on that button, that day's timestamp is recorded and is uploaded in firestore. And then I fetch the data from there and update a fl chart widget.
This is how I get the data from firebase, convert it to DateTime and send it to the graph building method.
Future<void> updateOfflineGraph(String uid) async {
//GraphData graphData = globalContext.watch<GraphData>();
GraphData graphData = GraphData();
List<dynamic> today = List<dynamic>();
List<DateTime> now = List<DateTime>();
try {
DocumentSnapshot _docSnapshot =
await _firestore.collection("graph").document(uid).get();
today.addAll(_docSnapshot.data()['dates']);
for (int i = 0; i < today.length; i++) {
now.add(DateTime.fromMicrosecondsSinceEpoch(
today[i].microsecondsSinceEpoch));
}
graphData.buildGraph(now);
} catch (e) {
print(e);
}
}
And this is how I process the data for the fl chart.
class GraphData with ChangeNotifier {
List<FlSpot> _data = List<FlSpot>();
List<int> _date = List<int>();
List<FlSpot> get data =>
List.unmodifiable(_data..sort((a, b) => a.x.compareTo(b.x)));
void addPoint(FlSpot spot) {
_data.add(spot);
notifyListeners();
}
void buildGraph(List<DateTime> dateTime) {
removeAllPoints();
int days = 0;
int month = dateTime[0].month;
for (int i = 0; i < dateTime.length; i++) {
if (dateTime[i].month == month) {
days++;
} else {
addMonth(days, month);
days = 0;
month = dateTime[i].month;
i--;
}
}
addMonth(days, month);
}
void addMonth(int days, int month) {
addPoint(FlSpot(month.toDouble(), days.toDouble()));
print(days);
print(month);
print(_data.length);
}
}
And then do this to update the graph.
LineChartBarData(
spots:
// [
// FlSpot(1, 3),
// FlSpot(2, 4),
// FlSpot(4, 5.5),
// FlSpot(5, 1),
// FlSpot(8, 4),
// FlSpot(12, 3),
// ],
context.watch<GraphData>().data.length > 0
? context.watch<GraphData>().data
: [FlSpot(0.0, 0.0)],
}
The problem that I'm facing is that when I do this whole thing, the points are stored in the _data list successfully, but when I try to call spots in LineChartBarData, it says that _data is null when it is called. I don't know why is this happening as the data was there in an iteration before.