ChartLegend.fromDataSets constructor

ChartLegend.fromDataSets(
  1. List<ChartDataSet> dataSets, {
  2. Key? key,
  3. Set<Color> hidden = const <Color>{},
  4. ValueChanged<Color>? onToggle,
  5. ChartTheme? theme,
  6. Axis direction = Axis.horizontal,
  7. String seriesLabelFor(
    1. Color color,
    2. List<ChartDataSet> group
    )?,
})

Construct a legend from a list of ChartDataSets, grouped by color.

If multiple datasets share a color, the first one's dataPoint.label is used for the series label. Pass seriesLabelFor to control the label explicitly (for example, looking it up in an external map keyed by color).

Implementation

factory ChartLegend.fromDataSets(
  List<ChartDataSet> dataSets, {
  Key? key,
  Set<Color> hidden = const <Color>{},
  ValueChanged<Color>? onToggle,
  ChartTheme? theme,
  Axis direction = Axis.horizontal,
  String Function(Color color, List<ChartDataSet> group)? seriesLabelFor,
}) {
  final grouped = <Color, List<ChartDataSet>>{};
  for (final set in dataSets) {
    grouped.putIfAbsent(set.color, () => <ChartDataSet>[]).add(set);
  }
  final items = [
    for (final entry in grouped.entries)
      ChartLegendItem(
        color: entry.key,
        label: seriesLabelFor != null
            ? seriesLabelFor(entry.key, entry.value)
            : (entry.value.first.dataPoint.label ?? _defaultLabel(entry.key)),
      ),
  ];
  return ChartLegend(
    key: key,
    items: items,
    hidden: hidden,
    onToggle: onToggle,
    theme: theme,
    direction: direction,
  );
}