如何在Flutter中自定义条形图每个条形的颜色? [英] How to custom the color of each bar of a bar chart in flutter?
问题描述
我是新手,请尝试制作具有不同颜色的条形图.我使用谷歌提供的图表依赖.
I am new to flutter and try to build a bar chart with different colors. I use the chart dependency provided by google.
https://google.github.io/charts/flutter/gallery.html
但是,我发现我只能更改所有条形的颜色.无论如何,我可以自定义一个特定条形的颜色吗?我已经在网上搜索过,没有发布此类信息.
However, I find I could only change the color of all bars. Is there anyway I could custom the color of one specific bar? I have searched online and no such information are posted.
推荐答案
要扩展Hemanth所指的内容, colorFn
是一种采用返回颜色的函数的属性.
To expand on what Hemanth is referring to, colorFn
is a property that takes a function that returns a color.
因此,如果您执行以下操作:
So if you do something like:
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault
您将为系列中的每个细分返回相同的颜色.
You're going to be returning the same color for every segment in the series.
要为系列中的各个细分设置不同的颜色,您可以执行以下操作:
To set different colors for individual segments within a series you can do something like this:
class ExampleSegment {
final String segment;
final int size;
ExampleSegment(this.segment, this.size);
}
static List<charts.Series<ExampleSegment, String>> _createSampleData() {
final blue = charts.MaterialPalette.blue.makeShades(2);
final red = charts.MaterialPalette.red.makeShades(2);
final green = charts.MaterialPalette.green.makeShades(2);
final data = [
new ExampleSegment('First', 100),
new ExampleSegment('Second', 100),
new ExampleSegment('Third', 100),
new ExampleSegment('Fourth', 100),
];
return [
new charts.Series<ExampleSegment, String>(
id: 'Segments',
domainFn: (ExampleSegment segment, _) => segment.segment,
measureFn: (ExampleSegment segment, _) => segment.size,
data: data,
colorFn: (ExampleSegment segment, _) {
switch (segment.segment) {
case "First":
{
return blue[1];
}
case "Second":
{
return red[1];
}
case "Third":
{
return green[1];
}
case "Fourth":
{
return blue[0];
}
default:
{
return red[0];
}
}
}
),
];
}
这篇关于如何在Flutter中自定义条形图每个条形的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!