How to apply linear gradient in flutter charts?

3,685

Apparently there is no such functionality yet. I managed to get it working with the following code:

Widget _buildChart() {
  return Container(
    height: 300,
    child: ShaderMask(
      child: charts.BarChart(
        _createRandomData(),
        animate: true,
        primaryMeasureAxis: new charts.NumericAxisSpec(
            renderSpec: new charts.NoneRenderSpec(), showAxisLine: false),
        domainAxis: new charts.OrdinalAxisSpec(
            showAxisLine: false, renderSpec: new charts.NoneRenderSpec()),
        layoutConfig: new charts.LayoutConfig(
            leftMarginSpec: new charts.MarginSpec.fixedPixel(0),
            topMarginSpec: new charts.MarginSpec.fixedPixel(0),
            rightMarginSpec: new charts.MarginSpec.fixedPixel(0),
            bottomMarginSpec: new charts.MarginSpec.fixedPixel(0)),
        defaultRenderer: new charts.BarRendererConfig(
            cornerStrategy: const charts.ConstCornerStrategy(30)),
      ),
      shaderCallback: (Rect bounds) {
        return LinearGradient(
          begin: Alignment.bottomCenter,
          end: Alignment.topCenter,
          colors: [Color(0xFF51DE93), Color(0xFFFFB540), Color(0xFFFA4169)],
          stops: [
            0.0,
            0.5,
            1.0,
          ],
        ).createShader(bounds);
      },
      blendMode: BlendMode.srcATop,
    )
  );
}

Result: chart screenshot

Share:
3,685
Hari Prasath
Author by

Hari Prasath

Updated on December 11, 2022

Comments

  • Hari Prasath
    Hari Prasath over 1 year

    How to apply linear gradient in the flutter charts?

    I have tried with colors class but i am able to apply only a solid color and unable to find a way for using gradient in the graph bars.

    chart.Series<Person,String>(
        id:"Person3",
        colorFn:(_,__)=>chart.MaterialPalette.red.shadeDefault,
        domainFn: (Person dataPoint, _)=>dataPoint.name,
        measureFn: (Person dataPoint, _)=>dataPoint.no,
        data:data2,
      )
    

    Provide me some way to apply linear gradient

  • Hari Prasath
    Hari Prasath over 4 years
    I requested for charts. this one works for normal widgets, not for a chart library.
  • Shubham Narkhede
    Shubham Narkhede almost 3 years
    Thanks for the answer. But I'm having one query how to reduce height oh graph because when i used your code the size is not reduce it occupise whole height of page