Skip to content

Instantly share code, notes, and snippets.

@imaNNeo
Created June 20, 2024 22:15
Show Gist options
  • Save imaNNeo/bb9eb775b6df46c6fd52892942be2e0a to your computer and use it in GitHub Desktop.
Save imaNNeo/bb9eb775b6df46c6fd52892942be2e0a to your computer and use it in GitHub Desktop.
Adding/Removing charts
import 'dart:math';
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(
title: 'Line Chart Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static const _colors = [
Colors.red,
Colors.green,
Colors.blue,
Colors.yellow,
Colors.purple,
Colors.orange,
];
List<LineChartBarData> showingLines = [];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: AspectRatio(
aspectRatio: 2.0,
child: LineChart(
LineChartData(
lineBarsData: showingLines,
minX: 0,
maxX: 6,
minY: 0,
maxY: 10,
gridData: const FlGridData(show: true),
),
),
),
),
floatingActionButton: Column(
mainAxisSize: MainAxisSize.min,
children: [
FloatingActionButton(
onPressed: _addLine,
child: const Icon(Icons.add),
),
const SizedBox(height: 12),
FloatingActionButton(
onPressed: _removeLine,
child: const Icon(Icons.remove),
),
],
),
);
}
void _addLine() {
final color = _colors[showingLines.length % _colors.length];
final List<FlSpot> spots = [];
for (int i = 0; i < 7; i++) {
spots.add(FlSpot(
i.toDouble(),
Random().nextInt(10).toDouble(),
));
}
final LineChartBarData lineChartBarData = LineChartBarData(
spots: spots,
isCurved: true,
color: color,
barWidth: 2,
isStrokeCapRound: true,
belowBarData: BarAreaData(show: false),
);
setState(() {
showingLines.add(lineChartBarData);
});
}
void _removeLine() {
if (showingLines.isNotEmpty) {
setState(() {
showingLines.removeLast();
});
}
}
}
@imaNNeo
Copy link
Author

imaNNeo commented Jun 20, 2024

CleanShot.2024-06-21.at.00.14.22.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment