How to custom the color of each bar of a bar chart in flutter?

4,874

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];
              }
          }
        }
      ),
  ];
}

Share:
4,874
xenophon123
Author by

xenophon123

Updated on December 11, 2022

Comments

  • xenophon123
    xenophon123 over 1 year

    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.