Articles in this section
Category / Section

How to Create Multiple Legend Items for Single Column Series in Flutter Cartesian Charts?

7 mins read

This article demonstrates how to create multiple cartesian legend items for a single ColumnSeries and customize segment colors and borders using the Flutter SfCartesianChart.

To achieve the desired visualization of more than one legend item in the ColumnSeries, you can utilize the onCreateRenderer callback. Create a CustomColumnSeriesRenderer by extending ColumnSeriesRenderer and override the buildLegendItems method. This callback allows you to create custom cartesian legend items and manage their interactions more effectively. The _handleLegendItemTapped method customizes cartesian legend items and handles legend item taps to toggle segment visibility.
To further refine the appearance of the segments within the ColumnSeries, you can use the onCreateShader method. This method enables you to create a gradient shader, allowing you to specify the desired colors and borders for the segments, resulting in a more visually appealing and customized chart.

The following steps outline how to create multiple cartesian legend items for a single column series and customize segment colors and borders:

Step 1: Import required packages.

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'dart:ui' as ui;
import 'package:syncfusion_flutter_core/core.dart';
import 'package:syncfusion_flutter_charts/src/charts/common/core_legend.dart';

Step 2: Define datasets list for the series that will be used in thee ColumnSeries.

  • _data: This is a list of data points, where each entry represents sales data for a month. Some values are positive, while others are negative.
  • _midValue: This variable is used to calculate the midpoint for the gradient in the column chart, determining where the segment color should transition from green to red.
  final List<_ChartData> _data = [
    _ChartData('Jan', 35),
    _ChartData('Feb', -35),
    _ChartData('Mar', 28),
    _ChartData('Apr', -34),
    _ChartData('May', 34),
    _ChartData('Jun', -32),
    _ChartData('July', 32),
    _ChartData('Aug', -40),
    _ChartData('Sep', 40),
    _ChartData('Oct', -28),
    _ChartData('Nov', 30),
    _ChartData('Dec', -38),
  ];
  double _midValue = 0;

Step 3: Configure the chart and define the data series. Creates a SfCartesianChart with a ColumnSeries that visualizes chart data. The onActualRangeChanged callback adjusts a mid-value based on the visible range of the vertical axis, which is then used in the onCreateShader method to apply a gradient shader to the columns, transitioning from green at the top to red at the bottom. This gradient changes dynamically depending on the data range.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SfCartesianChart(
        primaryXAxis: const CategoryAxis(),
        legend: const Legend(isVisible: true),
        onActualRangeChanged: (ActualRangeChangedArgs rangeChangedArgs) {
          if (rangeChangedArgs.orientation == AxisOrientation.vertical) {
            _midValue = rangeChangedArgs.visibleMax /
                (rangeChangedArgs.visibleMax.abs() +
                    rangeChangedArgs.visibleMin.abs());
          }
        },
        series: <CartesianSeries<_ChartData, String>>[
          ColumnSeries<_ChartData, String>(
            dataSource: _data,
            xValueMapper: (_ChartDatadata, int index) => data.year,
            yValueMapper: (_ChartDatadata, int index) => data.sales,
            color: Colors.green.withValues(alpha: 0.4),
            onCreateShader: (ShaderDetails details) {
              return ui.Gradient.linear(
                details.rect.topCenter,
                details.rect.bottomCenter,
                <Color>[
                  Colors.green,
                  Colors.green,
                  Colors.red,
                  Colors.red,
                ],
                <double>[
                  0,
                  _midValue,
                  _midValue,
                  1,
                ],
              );
            },
            borderColor: Colors.green,
            onCreateRenderer: (ChartSeries series) {
              return _CustomColumnSeriesRenderer();
            },
          ),
        ],
      ),
    );
  }

Step 4: Create custom column series renderer. The _CustomColumnSeriesRenderer class extends the ColumnSeriesRenderer to customize how cartesian legend items are created and interacted with in a SfCartesianChart. It creates two cartesian legend items, positive and negative, each associated with green and red colors, respectively. Tapping on these cartesian legend items toggles the visibility of the corresponding positive or negative segments in the column series.

class _CustomColumnSeriesRenderer<T, D> extends ColumnSeriesRenderer<T, D> {
  _CustomColumnSeriesRenderer();

  final List<String> _legendText = ['Positive', 'Negative'];
  final List<Color> _iconPalette = [Colors.green, Colors.red];
  bool _positiveVisible = true;
  bool _negativeVisible = true;

  @override
  List<CartesianLegendItem>? buildLegendItems(int index) {
    return List<CartesianLegendItem>.generate(_legendText.length, (index) {
      return CartesianLegendItem(
        text: _legendText[index],
        seriesIndex: this.index,
        iconType: ShapeMarkerType.rectangle,
        iconColor: _iconPalette[index],
        onTap: (LegendItem item, bool isToggled) {
          _handleLegendItemTapped(index);
        },
        iconBorderWidth: 1,
      );
    });
  }

  void _handleLegendItemTapped(int index) {
    if (index == 0) {
      _positiveVisible = !_positiveVisible;
    } else {
      _negativeVisible = !_negativeVisible;
    }

    for (final ChartSegment segment in segments) {
      ColumnSegment columnSegment = segment as ColumnSegment;
      columnSegment.isVisible =
          columnSegment.y.isNegative ? _negativeVisible : _positiveVisible;
    }

    markNeedsUpdate();
  }

  @override
  ColumnSegment<T, D> createSegment() {
    return _CustomColumnSegment<T, D>();
  }
}

Step 5: Define a custom column segment to control segment visibility during rendering.

class _CustomColumnSegment<T, D> extends ColumnSegment<T, D> {
  _CustomColumnSegment();

  @override
  void onPaint(Canvas canvas) {
    if (!isVisible) {
      return;
    }
    super.onPaint(canvas);
  }
}

By following these steps and the provided code snippet, you can successfully add more than one legend item for a single column series and customize both the color and border of the segments.

column_series.gif

View the Github Sample here.
.
Conclusion

I hope you enjoyed learning about how to create cartesian legend items for Flutter CartesianCharts column series.
You can refer to our Flutter CartesianChart feature tour page to learn about its other groundbreaking feature representations. You can also explore our documentation to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied