Created
June 20, 2024 22:15
-
-
Save imaNNeo/bb9eb775b6df46c6fd52892942be2e0a to your computer and use it in GitHub Desktop.
Adding/Removing charts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
CleanShot.2024-06-21.at.00.14.22.mp4