Contents
Coding With Dhrumil

HomeArticles

Flutter Charts: Build Custom Graphs Without a Library

By Dhrumil PatelPublished 4 min read

Most Flutter chart tutorials start and end with a package import. That works until you need a visual that no package supports, or your chart janks while scrolling. This guide takes the other route: drawing charts yourself with CustomPainter, so you understand every pixel and can tune performance deliberately.

We will build a line chart, a bar chart, and a pie chart, then look at when a package still makes sense. All code targets current stable Flutter and runs on Android and iOS without platform channels.

Why Draw Charts With CustomPainter

CustomPainter gives you a Canvas and a Size, nothing else. You map data values to pixel coordinates yourself, which sounds like extra work until you hit real requirements: a reference line at a specific threshold, a shaded range, an annotation that follows a data point. Packages expose configuration objects for these; a painter just draws them.

The trade-off is time. A basic line chart is roughly 80-150 lines of code, a bar chart 60-100, and a pie chart 50-90 once you handle labels. Budget half a day for your first one and two hours for each variant after that. The payoff is a chart that matches your design system exactly.

Custom painters also keep your dependency count low. Every chart package adds to your bundle, and each one has its own gesture, tooltip, and animation APIs to learn. If your app needs one or two chart types, hand-rolling usually wins on total effort.

  • Full control over colors, typography, and spacing
  • No package-specific API to learn or migrate
  • Easy to add threshold lines and range shading
  • Smaller app size and fewer transitive dependencies

Setting Up the Canvas and Coordinate Mapping

Start with a CustomPaint widget wrapped in a SizedBox or AspectRatio so the painter receives a predictable size. Inside paint(), reserve padding for axis labels before computing the plot area. A typical layout uses 40-56 logical pixels on the left for Y labels and 24-32 at the bottom for X labels.

The core is a mapping function: value to Y pixel, index to X pixel. Compute min and max from your data, add 10-15 percent headroom so the top point is not flush against the edge, then linearly interpolate. Keep this in one helper class so the line, bar, and pie painters can share it.

Draw axes with drawLine and labels with TextPainter. TextPainter is the part people forget: call layout() with a max width, then paint at a position offset by the measured size. Reuse TextPainter instances where you can, since creating them per frame is measurable work on mid-range devices.

Chart approaches compared on typical app requirements
ApproachCode to first chartInteractivityApp size impactBest for
CustomPainter line chart80-150 linesYou implement tapsNoneBrand-specific visuals, sparklines
CustomPainter bar chart60-100 linesYou implement tapsNoneSimple comparisons, dashboards
CustomPainter pie/donut50-90 linesStatic by defaultNoneSmall summary breakdowns
General chart package20-40 linesBuilt-in tooltips, zoomAdds a dependencyData-heavy interactive screens
Native platform viewHigh setup costVariesLargerReusing an existing native chart

Building a Line Chart Step by Step

Create a Path, moveTo the first point, then lineTo each subsequent point. For smooth curves use cubicTo with control points at one-third and two-thirds of the horizontal gap; keep tension subtle or the line will overshoot real values. Stroke width of 2-3 logical pixels reads well at typical phone densities.

Fill under the line with a vertical gradient from about 20 percent opacity to zero. Close the path back to the baseline before filling. This single detail makes charts look intentional rather than unfinished, and it costs one extra Path operation.

Draw point markers only when the dataset is small, roughly 12 points or fewer. Above that, markers turn into noise and cost draw calls. If you need interactivity, wrap the CustomPaint in a GestureDetector, convert the tap offset back through your inverse mapping, and highlight the nearest index. That inverse function is the mirror of your value-to-pixel helper.

  • Use Path.lineTo for straight segments, cubicTo for curves
  • Fill with a gradient at 15-25 percent starting opacity
  • Show dots only up to about 12 data points
  • Reuse one Paint object across the whole chart

Bar and Pie Charts Without Surprises

For bars, compute a slot width from plot width divided by item count, then draw a rect per item with 20-30 percent gap. Rounded corners come from RRect with a radius of 4-8 pixels. Grouped or stacked bars are just smaller rects inside the same slot, so the same painter scales to more complex layouts.

Pie and donut charts use drawArc with a sweep angle proportional to each value. Start at -pi/2 so the first slice begins at twelve o'clock, and add a 0.01-0.02 radian gap between slices for readability. For a donut, draw a second filled circle in the background color over the center, or stroke arcs with a thick stroke width.

Labels are where pie charts get hard. Place them outside the radius with a leader line, or skip them and use a legend below the chart. Legends are more readable on small screens and far easier to lay out, so default to a legend unless your designer insists otherwise.

35Sparkline80Bar70Pie/donut120Line with axes320Interactive line
Approximate lines of code to a working chart (lines)

Performance and State Handling

CustomPainter has a shouldRepaint method. Return true only when the data or theme actually changed; returning true unconditionally repaints on every frame and is the most common cause of chart jank. Compare list identity or a revision counter rather than deep-equality on every field.

Keep the painter free of expensive work. Precompute normalized points in the widget that owns the data, not inside paint(), which can be called many times per second during animations. For animated transitions, use an AnimationController and pass its value into the painter so shouldRepaint compares the animation value.

If your screen also holds long lists or forms, the same state discipline applies. Our guide on handling configuration changes in Kotlin without losing state covers the native side, and StatelessWidget vs StatefulWidget helps you decide where chart data should live in Flutter.

When to Use a Chart Package Instead

Reach for a package when you need pinch-to-zoom, panning, tooltips on hover, or accessibility semantics out of the box. Those features are each a day or more of work to do well by hand, and they are exactly where hand-rolled charts feel unfinished.

A middle path works well: use a package for the interactive, data-dense screen and custom painters for small sparklines and summary widgets. Sparklines in particular are 30-50 lines of painter code and appear in many places, so a shared painter pays for itself quickly.

Whatever you choose, profile in release mode on a mid-range device. Debug builds hide repaint costs, and a chart that scrolls smoothly in debug can stutter in the field.

Key points

  • CustomPainter gives full visual control at the cost of 60-150 lines per chart type.
  • Map values to pixels in one reusable helper and keep shouldRepaint strict.
  • Precompute normalized data outside paint() and reuse Paint and TextPainter objects.
  • Use a package when you need zoom, tooltips, and accessibility on data-dense screens.

Flutter Screen Widget and Cost Estimator

Estimate the number of widgets in a screen and a rough development-hour figure from your component counts. Adjust the fields to see how each UI area affects the total effort.

Calculate

Dhrumil Patel

Editor and Flutter contributor

Writes practical Flutter tutorials focused on widgets, layout and animation. Enjoys breaking large UI problems into small, testable pieces and explaining them clearly to beginners.

Related articles

Handling Configuration Changes in Kotlin Without Losing State

Explains rotation and process death scenarios and which save and restore pattern fits each.

How Many Widgets Does a Typical Flutter Screen Really Use?

Counts the widget tree size of common screen patterns and explains why composition beats deep nesting.

StatelessWidget vs StatefulWidget: Which One Should You Pick?

A side-by-side comparison of lifecycle, rebuild cost and when each choice keeps code simpler.