Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 73 ยท Animation and graphics

Charts in Flutter

Draw line, bar and pie charts in Flutter with fl_chart, understand how data maps to pixels and axis ticks, add touch tooltips, and know when to paint your own.

Dashboards, fitness apps and finance screens all need charts. Flutter does not include a chart widget, but the ecosystem does: fl_chart is a popular, free package that draws line, bar, pie, scatter and radar charts with CustomPaint under the hood. This lesson shows the three most common charts, then looks at the math every chart library performs so you can reason about axes, scaling and labels.

Real vs stand-in. The Dart is real fl_chart code and read-only, since the site cannot run Flutter and the package API changes between versions (check pub.dev for the version you install). The live examples are JavaScript stand-ins of the math under a chart: mapping data to pixels, choosing "nice" tick values, and turning values into pie angles.

Install

YAML
dependencies:
  fl_chart: ^1.0.0   # use the latest version from pub.dev

Every chart is a widget that takes a ...ChartData object describing what to draw. The data object is immutable and rebuilt on every build, and the widget animates between old and new data when it changes.

A line chart

DART
SizedBox(
  height: 220,
  child: LineChart(
    LineChartData(
      minX: 0, maxX: 6,
      minY: 0, maxY: 100,
      gridData: const FlGridData(show: true, drawVerticalLine: false),
      borderData: FlBorderData(show: false),
      titlesData: FlTitlesData(
        topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
        rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            interval: 1,
            getTitlesWidget: (value, meta) {
              const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
              return SideTitleWidget(meta: meta, child: Text(days[value.toInt()]));
            },
          ),
        ),
      ),
      lineBarsData: [
        LineChartBarData(
          spots: const [
            FlSpot(0, 40), FlSpot(1, 55), FlSpot(2, 48),
            FlSpot(3, 70), FlSpot(4, 66), FlSpot(5, 90), FlSpot(6, 82),
          ],
          isCurved: true,
          barWidth: 3,
          dotData: const FlDotData(show: false),
          belowBarData: BarAreaData(show: true, color: Colors.indigo.withValues(alpha: 0.15)),
        ),
      ],
    ),
  ),
)

Data points are FlSpot(x, y) in data space, not pixels. The chart needs a bounded height, so give it a SizedBox or AspectRatio (constraints). Axis labels come from titlesData: each axis gets SideTitles with a builder that turns a value into a widget. Fix minY and maxY to stop the chart rescaling as data changes, or leave them out to autoscale.

A bar chart

DART
BarChart(
  BarChartData(
    alignment: BarChartAlignment.spaceAround,
    maxY: 20,
    barGroups: [
      for (var i = 0; i < sales.length; i++)
        BarChartGroupData(
          x: i,
          barRods: [
            BarChartRodData(
              toY: sales[i].toDouble(),
              width: 18,
              borderRadius: const BorderRadius.vertical(top: Radius.circular(4)),
              color: Theme.of(context).colorScheme.primary,
            ),
          ],
        ),
    ],
  ),
)

A group is one x position, and it may hold several rods for side-by-side series. Stacked bars use rodStackItems.

A pie chart

DART
PieChart(
  PieChartData(
    sectionsSpace: 2,
    centerSpaceRadius: 48,        // > 0 makes a donut
    sections: [
      PieChartSectionData(value: 45, title: '45%', color: Colors.indigo, radius: 60),
      PieChartSectionData(value: 30, title: '30%', color: Colors.teal, radius: 60),
      PieChartSectionData(value: 25, title: '25%', color: Colors.orange, radius: 60),
    ],
  ),
)

Each section's sweep is its value divided by the sum of all values, so the values need not add up to 100. The package can also let you touch a section and react (pieTouchData); the common pattern is to enlarge the touched section's radius.

Touch and tooltips

Each chart has a touch config. A line chart shows a tooltip bubble by default; you can customize it:

DART
lineTouchData: LineTouchData(
  touchTooltipData: LineTouchTooltipData(
    getTooltipItems: (spots) => [
      for (final s in spots) LineTooltipItem('${s.y.toStringAsFixed(0)} pts', const TextStyle(color: Colors.white)),
    ],
  ),
),

Touch is a gesture event on the paint area, the same idea as Gestures and input handling. Class names inside tooltips change between versions of the package, so follow the version's own example app.

What every chart does: data to pixels

A chart's core is a linear scale: a function that maps a data range to a pixel range, with the y axis flipped because screen y grows downward. It also decides tick values so labels are "nice" numbers like 0, 20, 40 rather than 0, 17.3, 34.6.

JS Scale data to pixels and pick nice ticks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Pie sections: value to angle and percent

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When to use something else

  • Large datasets (thousands of points) or zoom and pan: fl_chart can be heavy; consider decimating the data, or a package built for performance.
  • Financial charts, gauges, maps: syncfusion_flutter_charts is feature-rich but has a commercial license for many uses; read it before adopting.
  • One simple sparkline or progress ring: write a CustomPainter yourself (CustomPaint and Canvas) with the same scale function above. It is 30 lines and adds no dependency.
  • Accessibility: a chart is a picture. Provide a Semantics label summarizing the trend or a data table alternative (accessibility).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the y axis flipped when you map data to pixels?

    Pixel y increases downward, so the scale maps the maximum value to the smallest pixel y.
  2. 2. How does PieChart decide each section's angle?

    Values are proportions of the total, so they need not add up to 100.
  3. 3. A LineChart inside a Column throws a layout error. What is the likely fix?

    Charts want a bounded size. In a Column the height is unbounded, so wrap the chart.
  4. 4. What is a good way to avoid a chart rescaling when data changes?

    Fixed bounds keep the axis stable; leaving them out makes the chart autoscale.

Summary

  • fl_chart offers LineChart, BarChart and PieChart; each takes an immutable data object and animates between versions.
  • Data lives in data space (FlSpot); a linear scale with a flipped y maps it to pixels, and nice ticks make readable axes.
  • Give charts a bounded size, add a text alternative for accessibility, and write a small CustomPainter when a package is overkill.

Next: Lottie and Rive Animations