Flutter Mobile Development · Lekcja

Tworzenie interaktywnego niestandardowego widgetu wykresu

Połącz CustomPainter z wykrywaniem gestów, aby renderować reagujący na dotyk wykres danych

Lekcja 2 z 413 kroki

Tworzenie interaktywnego niestandardowego widgetu wykresu to bezpłatna lekcja Flutter Mobile Development na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Flutter Mobile Development, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Flutter Mobile Development zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Why an Interactive Custom Chart?

Flutter ships with no built-in chart widget. When you need a touch-responsive bar or line chart that exactly matches your design, you combine two primitives:

  • CustomPainter — draws the chart onto a Canvas.
  • GestureDetector — captures taps and drags so the user can highlight or inspect data points.

In this lesson we build a bar chart that highlights the bar the user touches and reports its value. The key idea: the painter is a pure function of state, and gestures change that state.

The Data Model

Start with a plain immutable model. Keeping it framework-free makes it easy to test and reason about. Each bar has a label and a value.

This snippet is pure Dart with no Flutter imports, so it runs standalone.

class Bar {
  final String label;
  final double value;
  const Bar(this.label, this.value);
}

void main() {
  final data = <Bar>[
    const Bar('Mon', 12),
    const Bar('Tue', 30),
    const Bar('Wed', 8),
    const Bar('Thu', 22),
  ];
  final maxValue = data.map((b) => b.value).reduce((a, b) => a > b ? a : b);
  print('Bars: ${data.length}, max value: $maxValue');
  for (final b in data) {
    final ratio = (b.value / maxValue * 100).toStringAsFixed(0);
    print('${b.label}: $ratio% of tallest');
  }
}

Skeleton of a CustomPainter

A CustomPainter implements two methods:

  • paint(Canvas canvas, Size size) — where you draw.
  • shouldRepaint(old) — return true when inputs changed so Flutter repaints.

Pass your data and any interaction state (like the highlighted index) into the painter's constructor as final fields.

class BarChartPainter extends CustomPainter {
  final List<Bar> bars;
  final int? highlightedIndex;

  BarChartPainter({required this.bars, this.highlightedIndex});

  @override
  void paint(Canvas canvas, Size size) {
    // drawing logic goes here
  }

  @override
  bool shouldRepaint(covariant BarChartPainter old) {
    return old.bars != bars || old.highlightedIndex != highlightedIndex;
  }
}

Computing Bar Geometry

Before drawing, map each data value to pixel coordinates. Given the canvas size, divide the width into equal slots and scale heights against the maximum value.

Storing each bar's Rect lets you reuse the exact same geometry later for hit-testing — drawing and gestures must agree.

List<Rect> computeBarRects(List<Bar> bars, Size size) {
  final maxValue = bars.map((b) => b.value).reduce((a, b) => a > b ? a : b);
  final slotWidth = size.width / bars.length;
  const barFraction = 0.6; // bars take 60% of their slot
  final rects = <Rect>[];
  for (var i = 0; i < bars.length; i++) {
    final barWidth = slotWidth * barFraction;
    final left = i * slotWidth + (slotWidth - barWidth) / 2;
    final height = (bars[i].value / maxValue) * size.height;
    final top = size.height - height;
    rects.add(Rect.fromLTWH(left, top, barWidth, height));
  }
  return rects;
}

Drawing the Bars

Inside paint, build a Paint object and call canvas.drawRect for each bar. Use the highlightedIndex to give the touched bar a distinct color.

Tip: create paints once outside the loop when their properties don't change, and only swap the color per bar.

@override
void paint(Canvas canvas, Size size) {
  final rects = computeBarRects(bars, size);
  final paint = Paint()..style = PaintingStyle.fill;
  for (var i = 0; i < rects.length; i++) {
    paint.color = (i == highlightedIndex)
        ? const Color(0xFFFF7043) // highlighted
        : const Color(0xFF42A5F5); // default
    final rounded = RRect.fromRectAndRadius(
      rects[i],
      const Radius.circular(4),
    );
    canvas.drawRRect(rounded, paint);
  }
}

Drawing Labels with TextPainter

Canvas cannot draw text directly — you use a TextPainter. Lay out the text, then paint it at the position you want. Center each label under its bar.

void drawLabel(Canvas canvas, String text, Offset center) {
  final tp = TextPainter(
    text: TextSpan(
      text: text,
      style: const TextStyle(color: Color(0xFF333333), fontSize: 12),
    ),
    textDirection: TextDirection.ltr,
  )..layout();
  final offset = Offset(center.dx - tp.width / 2, center.dy);
  tp.paint(canvas, offset);
}

Hosting the Painter in a Widget

Wrap your painter in a CustomPaint widget. Give it a size (or let it expand) so it has bounds to draw within.

Because the highlight is interaction state, the host is a StatefulWidget that holds _highlightedIndex and rebuilds when it changes.

class BarChart extends StatefulWidget {
  final List<Bar> bars;
  const BarChart({super.key, required this.bars});
  @override
  State<BarChart> createState() => _BarChartState();
}

class _BarChartState extends State<BarChart> {
  int? _highlightedIndex;

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: const Size(double.infinity, 200),
      painter: BarChartPainter(
        bars: widget.bars,
        highlightedIndex: _highlightedIndex,
      ),
    );
  }
}

Hit-Testing a Tap

To know which bar was touched, recompute the same rects and test which one contains the touch point. A pure helper keeps this logic testable and identical to what the painter drew.

This snippet is standalone Dart — it models a rectangle and the same hit-test math the widget uses.

class Box {
  final double left, top, width, height;
  const Box(this.left, this.top, this.width, this.height);
  bool contains(double x, double y) =>
      x >= left && x <= left + width && y >= top && y <= top + height;
}

int? hitTest(List<Box> boxes, double x, double y) {
  for (var i = 0; i < boxes.length; i++) {
    if (boxes[i].contains(x, y)) return i;
  }
  return null;
}

void main() {
  final boxes = [
    const Box(0, 100, 40, 100),
    const Box(60, 50, 40, 150),
    const Box(120, 120, 40, 80),
  ];
  print(hitTest(boxes, 70, 90));   // 1
  print(hitTest(boxes, 200, 10));  // null
}

Wiring Up GestureDetector

Wrap the CustomPaint in a GestureDetector. Use onTapDown to read the local touch position, run the hit-test, and call setState to update the highlight.

Use details.localPosition (already relative to the widget), not the global position.

@override
Widget build(BuildContext context) {
  return GestureDetector(
    onTapDown: (details) {
      final size = context.size!;
      final rects = computeBarRects(widget.bars, size);
      final p = details.localPosition;
      int? hit;
      for (var i = 0; i < rects.length; i++) {
        if (rects[i].contains(p)) { hit = i; break; }
      }
      setState(() => _highlightedIndex = hit);
    },
    child: CustomPaint(
      size: const Size(double.infinity, 200),
      painter: BarChartPainter(
        bars: widget.bars,
        highlightedIndex: _highlightedIndex,
      ),
    ),
  );
}

Responding to Drags

For a scrubbing experience (drag a finger across bars to inspect each), handle onPanUpdate in addition to onTapDown. The same hit-test runs continuously as the finger moves.

Wrap the highlight update in a helper so tap and drag share one code path.

void _updateHighlight(Offset local) {
  final size = context.size!;
  final rects = computeBarRects(widget.bars, size);
  int? hit;
  for (var i = 0; i < rects.length; i++) {
    if (rects[i].contains(local)) { hit = i; break; }
  }
  if (hit != _highlightedIndex) {
    setState(() => _highlightedIndex = hit);
  }
}

// in build():
// onTapDown: (d) => _updateHighlight(d.localPosition),
// onPanUpdate: (d) => _updateHighlight(d.localPosition),

Showing the Selected Value

Now surface feedback. Below the chart, render a Text that reflects the highlighted bar, or draw a tooltip on the canvas above the selected bar.

  • Keep the painter stateless about UI text — pass it the highlighted index only.
  • Avoid heavy work in paint; precompute geometry and reuse it for both drawing and hit-testing.
  • Make shouldRepaint precise so you don't repaint on every frame.
Widget _selectionLabel() {
  if (_highlightedIndex == null) {
    return const Text('Tap a bar to inspect');
  }
  final bar = widget.bars[_highlightedIndex!];
  return Text('${bar.label}: ${bar.value.toStringAsFixed(1)}',
      style: const TextStyle(fontWeight: FontWeight.bold));
}

Quick Check

Test your understanding of how drawing and gesture handling stay consistent.

Recap

You built a touch-responsive chart by separating concerns:

  • Data model — plain, immutable, testable.
  • Geometry helper — one function maps values to Rects, shared by drawing and hit-testing.
  • CustomPainter — draws bars and labels from data plus the highlighted index, with a precise shouldRepaint.
  • StatefulWidget — holds interaction state and calls setState.
  • GestureDetector — onTapDown and onPanUpdate run the shared hit-test on localPosition.

The golden rule: keep the painter a pure function of state, and let gestures be the only thing that mutates that state.

Bezpłatny start

Ucz się Dart dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
22
Lekcje
88

Często zadawane pytania

Czy lekcja „Tworzenie interaktywnego niestandardowego widgetu wykresu” jest bezpłatna?

Tak — pełny tekst „Tworzenie interaktywnego niestandardowego widgetu wykresu” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Flutter Mobile Development, przejdź na CoddyKit PRO. Kurs Flutter Mobile Development zawiera 4 lekcji w sumie.

Co nauczysz się w „Tworzenie interaktywnego niestandardowego widgetu wykresu”?

Połącz CustomPainter z wykrywaniem gestów, aby renderować reagujący na dotyk wykres danych Ćwiczysz Flutter Mobile Development z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Flutter Mobile Development?

Nie wymagamy żadnego doświadczenia. Flutter Mobile Development w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Tworzenie interaktywnego niestandardowego widgetu wykresu”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Flutter Mobile Development?

Tak. Każda lekcja Flutter Mobile Development zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. API Canvas: ścieżki, pędzle i shadery
  2. Tworzenie interaktywnego niestandardowego widgetu wykresu
  3. Przycinanie, tryby mieszania i komponowanie warstw
  4. Testowanie trafień i optymalizacja przemalowywania
← Powrót do Flutter Mobile Development