charts - 如何在 flutter 中自定义条形图每个条形的颜色?

标签 charts flutter dart

我是 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/

相关文章:

java - 使用 jfreechart 更改高于阈值的线条颜色

javascript - Y 轴上带有时间的 Chartjs 自定义图例

javascript - Highcharts 导出带有预选数据的 SVG

javascript - 使用媒体查询修改 yAxys 组件的行为

flutter - 返回类型 'FutureOr<Database>' 是 Fl​​utter 中潜在的不可空类型

flutter - 类中的Flutter插件构造函数无法应用于给定类型

flutter - 带有参数的Flutter StatefulWidget

firebase - 如何从嵌套子集合中监听更改(或获取流)?

android - 如何修复 "unexpected element <queries> found in <manifest>"错误?

flutter - 让用户使用Flutter登录Android设备