Flutter LineChartData and BarChartData with Firebase

63 Views Asked by At

I want to draw a line chart with fl_chart with data from Firestore. The fields are Amount, a double, and Date, a String which was picked from DateTime. I can't really get the line because it gets this error FormatException: Invalid double 10-Feb-2024. Can someone help correct the error or tell me how to better write the code?

FutureBuilder(
  future: FirebaseFirestore.instance
      .collectionGroup(widget.dailyTransactionsCollection)
      .get(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const CircularProgressIndicator();
    } else if (snapshot.hasError) {
      return Text(
        widget.errorString,
        style: const TextStyle(color: Colors.white),
      );
    }
    if (snapshot.hasData) {
      List<FlSpot> dataPoints = [];
      for (var doc in snapshot.data!.docs) {
        double amount = doc.get('Amount');
        String date = doc.get('Date');
        FlSpot dataPoint = FlSpot(double.parse(date), amount);
        dataPoints.add(dataPoint);
      }
      LineChartData(
        lineBarsData: [
          LineChartBarData(
            spots: dataPoints,
            isCurved: true,
            color: Colors.blue,
            barWidth: 2,
            dotData: const FlDotData(show: false),
          ),
        ],
        titlesData: const FlTitlesData(
          bottomTitles: AxisTitles(
              sideTitles:
                  SideTitles(reservedSize: 33, showTitles: true)),
          leftTitles:
              AxisTitles(sideTitles: SideTitles(reservedSize: 44)),
        ),
        gridData: const FlGridData(show: true),
      );
    }
    return Center(
      child: Text(widget.noDataYetString),
    );
  },
)

I want the date to reflect at the bottom and the amount to reflect on the left of the lineBar.

1

There are 1 best solutions below

3
Vladyslav Ulianytskyi On

Here you shouldn't parse date as double. If you dive into the FlSpot doc, you will notice that:

FlSpot(double x, double y)
x determines cartesian (axis based) horizontally position 0 means most left point of the chart
const

So, you should set x coordinate that is double. If you whant to show it on chart, you must determine by what rule to convert the date into a number for display on the coordinate axis. E.g. for the first date set 1.0, second - 2.0 etc:

var x = 1.0;
for (var doc in snapshot.data!.docs) {
        double amount = doc.get('Amount');
        String date = doc.get('Date');
        FlSpot dataPoint = FlSpot(x, amount);
        dataPoints.add(dataPoint);
        x = x + 1;
      }

Another thing is that you need to sign these points as dates. Try this solution.