【问题标题】:How to custom the color of each bar of a bar chart in flutter?如何在颤动中自定义条形图的每个条形的颜色?
【发布时间】:2019-10-27 21:03:54
【问题描述】:

我是 Flutter 的新手,我尝试用不同的颜色构建条形图。我使用谷歌提供的图表依赖。

https://google.github.io/charts/flutter/gallery.html

但是,我发现我只能更改所有条形的颜色。无论如何我可以自定义一个特定条的颜色吗? 我在网上搜索过,没有发布此类信息。

【问题讨论】:

    标签: charts flutter dart


    【解决方案1】:

    为了扩展 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];
                  }
              }
            }
          ),
      ];
    }
    
    

    【讨论】:

    • 如果我想用随机的十六进制代码来制作呢?因为在我的情况下,我从 firebase 获得了这个系列,所以我不知道文件会有多少......
    【解决方案2】:

    Series 拥有一个colorFn 属性,您可以使用它指定笔划。

    检查this

    希望有帮助!

    【讨论】:

    • 谢谢。但我认为它只会改变所有条的颜色。我可以只改变一个条的颜色吗?
    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2023-04-09
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多