在charts_flutter中将图表数值设置为100,并默认将每个柱状图尺寸从60调整为100的实现方法
Got it, let's break down how to handle both of your configuration needs for the charts_flutter package:
1. Set All Chart Values to 100
You have two straightforward ways to make every bar display a value of 100:
Update your data source directly: If you want to permanently set the values in your dataset, modify each
BarChartModelentry in yourdatalist so thefinancialproperty equals 100:List<BarChartModel> data = [ BarChartModel(year: '2020', financial: 100, color: charts.MaterialPalette.blue.shadeDefault), BarChartModel(year: '2021', financial: 100, color: charts.MaterialPalette.red.shadeDefault), // Add remaining entries with financial: 100 ];Hardcode the value in the measure function: If you don't want to alter your original data, override the
measureFnin yourcharts.Seriesto return 100 directly:List<charts.Series<BarChartModel, String>> series = [ charts.Series( displayName: "Students Marks", id: "Students Marks", data: data, domainFn: (BarChartModel series, _) => series.year, measureFn: (BarChartModel series, _) => 100, // Replace series.financial with 100 colorFn: (BarChartModel series, _) => series.color, ), ];
2. Adjust Bar Width from 60 to 100
To change the default bar size, you'll need to add a BarRendererConfig via the barRendererDecorator parameter when creating your BarChart widget. This lets you explicitly set the bar width in pixels:
charts.BarChart( series, animate: true, // Keep animation if you want it barRendererDecorator: charts.BarRendererConfig( barWidthPx: 100, // Set your desired width here ), )
Full Working Example
Here's how everything fits together in a complete code snippet:
// Your BarChartModel class (assuming it's defined like this) class BarChartModel { final String year; final int financial; final charts.Color color; BarChartModel({required this.year, required this.financial, required this.color}); } // Updated series configuration List<charts.Series<BarChartModel, String>> series = [ charts.Series( displayName: "Students Marks", id: "Students Marks", data: [ BarChartModel(year: '2020', financial: 100, color: charts.MaterialPalette.blue.shadeDefault), BarChartModel(year: '2021', financial: 100, color: charts.MaterialPalette.red.shadeDefault), ], domainFn: (BarChartModel series, _) => series.year, measureFn: (BarChartModel series, _) => series.financial, // Or use 100 directly colorFn: (BarChartModel series, _) => series.color, ), ]; // Build method with adjusted bar chart @override Widget build(BuildContext context) { return charts.BarChart( series, animate: true, barRendererDecorator: charts.BarRendererConfig( barWidthPx: 100, // Width adjusted from 60 to 100 ), ); }
内容的提问来源于stack exchange,提问作者swapnil mane

