我是 Flutter 的新手,尝试构建一个具有不同颜色的条形图。我使用谷歌提供的图表依赖。
https://google.github.io/charts/flutter/gallery.html
但是,我发现我只能更改所有条形的颜色。无论如何我可以自定义一个特定栏的颜色吗? 我在网上搜索过,没有发布这样的信息。
最佳答案
为了进一步说明 Hemanth 所指的内容,colorFn
是一个接受返回颜色的函数的属性。
所以如果你做这样的事情:
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault
您将为系列中的每个片段返回相同的颜色。
要为系列中的各个片段设置不同的颜色,您可以这样做:
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];
}
}
}
),
];
}
关于charts - 如何在 flutter 中自定义条形图每个条形的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56577613/