Creating a Line Bar Chart with Fixed-Distance Grid Lines using fl_chart

111 Views Asked by At

I'm working on developing a line bar chart in Flutter using the fl_chart package, where I need to include two bars for every X value. Additionally, I want to add grid lines that are at a fixed distance from the right bar and maintain the same distance for all bars. Currently, my chart looks like the one in the screenshot provided below. I've included an example of my code for reference.

enter image description here

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Chart example'),
        ),
        body: const Center(child: ChartExample()),
      ),
    );
  }
}

class ChartExample extends StatelessWidget {
  const ChartExample({super.key});

  @override
  Widget build(BuildContext context) {
    final incomeFactSpots = [
      const FlSpot(0, 10),
      const FlSpot(1, 5),
      const FlSpot(2, 15),
      const FlSpot(3, 10),
      const FlSpot(4, 20),
      const FlSpot(5, 15),
      const FlSpot(6, 25)
    ];
    final expenseFactSpots = [
      const FlSpot(0, 5),
      const FlSpot(1, 10),
      const FlSpot(2, 5),
      const FlSpot(3, 15),
      const FlSpot(4, 10),
      const FlSpot(5, 20),
      const FlSpot(6, 15)
    ];

    return AspectRatio(
      aspectRatio: 1.7,
      child: Padding(
        padding: const EdgeInsets.only(right: 8),
        child: BarChart(
          BarChartData(
            barGroups: [
              for (var i = 0; i < expenseFactSpots.length; i++) ...[
                BarChartGroupData(
                  x: i,
                  barRods: [
                    BarChartRodData(
                     toY: incomeFactSpots[i].y,
                      color: Colors.blue,
                    ),
                    BarChartRodData(
                     toY: expenseFactSpots[i].y,
                      color: Colors.yellow,
                    ),
                  ],
                ),
              ]
            ],
            borderData: FlBorderData(
              show: false,
            ),
            gridData: FlGridData(
              show: true,
              drawHorizontalLine: true,
              drawVerticalLine: true,
              verticalInterval: 1 / 7,
            ),
          ),
        ),
      ),
    );
  }
}

Could someone please help me achieve a specific grid line spacing for every bar in my line bar chart using fl_chart? Your guidance would be greatly appreciated.

0

There are 0 best solutions below