Skip to content

Instantly share code, notes, and snippets.

@kururu-abdo
Created December 4, 2024 15:25
Show Gist options
  • Save kururu-abdo/179bc2115dd077d858934fa73a7db82b to your computer and use it in GitHub Desktop.
Save kururu-abdo/179bc2115dd077d858934fa73a7db82b to your computer and use it in GitHub Desktop.
painter_line_chart.dart
import 'package:flutter/material.dart';
class ChartData {
final double x;
final double y;
ChartData(this.x, this.y);
}
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final List<ChartData> _data = [
ChartData(0.1, 0.3),
ChartData(0.2, 0.5),
ChartData(0.3, 0.7),
ChartData(0.4, 0.4),
ChartData(0.5, 0.6),
ChartData(0.6, 0.8),
ChartData(0.7, 0.5),
ChartData(0.8, 0.9),
ChartData(0.9, 0.7),
];
double _selectedX = -1;
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: GestureDetector(
onPanUpdate: (details) {
setState(() {
_selectedX = details.localPosition.dx;
});
},
onPanEnd: (_) {
setState(() {
_selectedX = -1;
});
},
child: CustomPaint(
size: Size(double.infinity, 300),
painter: LineChartPainter(_data, _selectedX),
),
)
),
);
}
}
class LineChartPainter extends CustomPainter {
final List<ChartData> dataPoints;
final double selectedX;
LineChartPainter(this.dataPoints, this.selectedX);
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.stroke
..strokeWidth = 2;
// Draw axes
final axisPaint = Paint()
..color = Colors.black
..strokeWidth = 1;
canvas.drawLine(Offset(0, size.height), Offset(size.width, size.height), axisPaint); // X-axis
canvas.drawLine(Offset(0, 0), Offset(0, size.height), axisPaint); // Y-axis
// Draw lines connecting data points
final path = Path();
for (var i = 0; i < dataPoints.length; i++) {
final point = dataPoints[i];
final x = point.x * size.width;
final y = size.height - (point.y * size.height); // Invert Y for correct orientation
if (i == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
}
canvas.drawPath(path, paint);
// Highlight selected point
if (selectedX != -1) {
for (var point in dataPoints) {
final x = point.x * size.width;
if ((x - selectedX).abs() < 10) {
final y = size.height - (point.y * size.height);
final highlightPaint = Paint()
..color = Colors.red
..style = PaintingStyle.fill;
canvas.drawCircle(Offset(x, y), 6, highlightPaint);
break;
}
}
}
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment