Skip to content

[syncfusion_flutter_charts] The color of unselected legend was quite dark #2355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
komhkomh opened this issue May 20, 2025 · 3 comments
Open
Labels
charts Charts component waiting for customer response Cannot make further progress until the customer responds.

Comments

@komhkomh
Copy link

Bug description

After I updated syncfusion_flutter_charts to 29.1.39, the color of unselected legend was quite dark and barely to see if legendItemBuilder was applied.

Steps to reproduce

It happened everytime if legendItemBuilder used.

Code sample

class _MyHomePage extends StatefulWidget {
  // ignore: prefer_const_constructors_in_immutables
  _MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<_MyHomePage> {
  List<_SalesData> data = [
    _SalesData('Jan', 35),
    _SalesData('Feb', 28),
    _SalesData('Mar', 34),
    _SalesData('Apr', 32),
    _SalesData('May', 40),
  ];

  List<RxBool> isSelected = [true.obs, true.obs, true.obs];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          //Initialize the chart widget
          SfCartesianChart(
            primaryXAxis: const CategoryAxis(),
            onLegendTapped: (legendTapArgs) {
              if (legendTapArgs.seriesIndex is int) {
                isSelected[legendTapArgs.seriesIndex ?? 0].toggle();
              }
            },
            // Enable legend
            legend:  Legend(
              isVisible: true,
              toggleSeriesVisibility: true,
              width: '100%',
              itemPadding: 0,
              alignment: ChartAlignment.near,
              position: LegendPosition.top,
              overflowMode: LegendItemOverflowMode.wrap,
              legendItemBuilder: (legendText, series, point, seriesIndex) {
                return LabeledCheckbox(
                  label: legendText,
                  isShowing: isSelected[seriesIndex],
                  color: series?.color,
                );
              },
            ),
            series: <CartesianSeries<_SalesData, String>>[
              ColumnSeries<_SalesData, String>(
                animationDuration: 0,
                dataSource: data,
                xValueMapper: (_SalesData sales, _) => sales.year,
                yValueMapper: (_SalesData sales, _) => sales.sales,
                name: 'Sales1',
                color: Colors.red,
              ),
              ColumnSeries<_SalesData, String>(
                dataSource: data,
                animationDuration: 0,
                xValueMapper: (_SalesData sales, _) => sales.year,
                yValueMapper: (_SalesData sales, _) => sales.sales - 10,
                name: 'Sales2',
                color: Colors.blue,
              ),
              ColumnSeries<_SalesData, String>(
                dataSource: data,
                animationDuration: 0,
                xValueMapper: (_SalesData sales, _) => sales.year,
                yValueMapper: (_SalesData sales, _) => sales.sales - 15,
                name: 'Sales3',
                color: Colors.green,
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _SalesData {
  _SalesData(this.year, this.sales);

  final String year;
  final double sales;
}

class LabeledCheckbox extends StatelessWidget {
  const LabeledCheckbox({
    Key? key,
    required this.label,

    // required this.value,
    // required this.onChanged,
    required this.color,
    required this.isShowing,
  }) : super(key: key);

  final String label;

  // final bool value;
  // final Function onChanged;
  final Color? color;
  final RxBool isShowing;
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(right: 8, bottom: 6),
      child: Obx(
        () => Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              width: 14,
              height: 14,
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xFF2E3138),
              ),
              alignment: Alignment.center,
              child: isShowing.value
                  ? (Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: color ?? Colors.white,
                      ),
                    ))
                  : Container(),
            ),
            Flexible(child: Text(label)),
          ],
        ),
      ),
    );
  }
}

Screenshots or Video

Image

Image

Image

Stack Traces

no stack trace

On which target platforms have you observed this bug?

Android

Flutter Doctor output

[√] Flutter (Channel stable, 3.29.3, on Microsoft Windows [版本 10.0.22621.3155],
locale zh-CN) [1,399ms]
• Flutter version 3.29.3 on channel stable at
D:\flutter_windows_3.29.3-stable\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision ea121f8859 (6 weeks ago), 2025-04-11 19:10:07 +0000
• Engine revision cf56914b32
• Dart version 3.7.2
• DevTools version 2.42.3

[√] Windows Version (11 专业版 64-bit, 22H2, 2009) [5.2s]

[√] Android toolchain - develop for Android devices (Android SDK version 35.0.0)
[3.7s]
• Android SDK at D:\Android\SDK
• Platform android-35, build-tools 35.0.0
• ANDROID_SDK_ROOT = D:\Android\SDK
• Java binary at: C:\Program Files\Android\Android Studio\jbr\bin\java
This is the JDK bundled with the latest Android Studio installation on
this machine.
To manually set the JDK path, use: flutter config --jdk-dir="path/to/jdk".
• Java version OpenJDK Runtime Environment (build 21.0.6+-13355223-b631.42)
• All Android licenses accepted.

[√] Chrome - develop for the web [831ms]
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[!] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.12.3)
[830ms]
• Visual Studio at D:\Microsoft Visual Studio2022
• Visual Studio Community 2022 version 17.12.35527.113
X Visual Studio is missing necessary components. Please re-run the Visual
Studio installer for the "Desktop development with C++" workload, and
include these components:
MSVC v142 - VS 2019 C++ x64/x86 build tools
- If there are multiple build tool versions available, install the
latest
C++ CMake tools for Windows
Windows 10 SDK

[√] Android Studio (version 2024.3) [16ms]
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 21.0.6+-13355223-b631.42)

[√] Connected device (5 available) [778ms]
• SM S9010 (mobile) • R5CTA17Q1MB • android-arm64 • Android 14 (API 34)
• sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64 • Android 12 (API 31) (emulator)
• Windows (desktop) • windows • windows-x64 • Microsoft
Windows [版本 10.0.22621.3155]
• Chrome (web) • chrome • web-javascript • Google
Chrome 136.0.7103.93
• Edge (web) • edge • web-javascript • Microsoft
Edge 136.0.3240.50

[√] Network resources [1,854ms]
• All expected network resources are available.

! Doctor found issues in 1 category.

@komhkomh komhkomh changed the title syncfusion_flutter_charts [syncfusion_flutter_charts] The color of unselected legend was quite dark May 20, 2025
@LavanyaGowtham2021 LavanyaGowtham2021 added charts Charts component open Open labels May 20, 2025
@Mugunthan-Ramalingam
Copy link
Contributor

Mugunthan-Ramalingam commented May 22, 2025

Hi @komhkomh,

We have analyzed your case, and suspect that the toggled legend item's color may have been set too close to the chart background, making it appear very dark when unselected. Currently, we do not provide direct support for customizing the color of disabled legend items. However, you can achieve this effect by managing series visibility manually through external toggle controls that update each series isVisible property via its ChartSeriesController and customize the toggle color accordingly. This workaround gives you full control over the disabled legend appearance. We have shared a modified code snippets and sample for your reference.

child: SfCartesianChart(
 primaryXAxis: const CategoryAxis(),
 series: <CartesianSeries<ChartData, String>>[
   _buildColumnSeries(
     name: 'Series 1',
     dataSource: chartData2016,
     color: _seriesColors[0],
     controller: (controller) => _firstController = controller,
   ),
   _buildColumnSeries(
     name: 'Series 2',
     dataSource: chartData2017,
     color: _seriesColors[1],
     controller: (controller) => _secondController = controller,
   ),
   _buildColumnSeries(
     name: 'Series 3',
     dataSource: chartData2018,
     color: _seriesColors[2],
     controller: (controller) => _thirdController = controller,
   ),
 ],
),
 
ColumnSeries<ChartData, String> _buildColumnSeries({
 required String name,
 required List<ChartData> dataSource,
 required Color color,
 required void Function(ChartSeriesController controller) controller,
}) {
 return ColumnSeries<ChartData, String>(
   name: name,
   dataSource: dataSource,
   color: color,
   xValueMapper: (ChartData data, _) => data.x,
   yValueMapper: (ChartData data, _) => data.y,
   onRendererCreated: controller,
 );
}
 
Widget _buildToggleButton({
 required String label,
 required ValueNotifier<bool> isDisabled,
 required Color color,
 required ChartSeriesController Function() controller,
}) {
 return ValueListenableBuilder<bool>(
   valueListenable: isDisabled,
   builder: (context, value, _) {
     return GestureDetector(
       onTap: () {
         final ChartSeriesController<dynamic, dynamic> seriesController =
             controller();
         seriesController.isVisible = !seriesController.isVisible;
         isDisabled.value = !isDisabled.value;
       },
       child: Row(
         children: [
           Icon(
             Icons.bar_chart,
             size: 20,
             color: value ? Colors.red : color,
           ),
           const SizedBox(width: 4),
           Text(
             label,
             style: TextStyle(
               fontSize: 16,
               color: value ? Colors.red : color,
               fontWeight: FontWeight.w600,
             ),
           ),
         ],
       ),
     );
   },
 );

Output:

Image

UG Link: Callbacks in Flutter Cartesian Charts widget | Syncfusion

Please check and get back to us if you require further assistance.

Sample: gh2355.zip

Regards,
Mugunthan.

@komhkomh
Copy link
Author

komhkomh commented May 22, 2025

Thanks! @Mugunthan-Ramalingam It's an excellent way to custom the legends. However, I used the same chartSeriesController for all series, because I needed to calculate the size of plotarea in the onActualRangeChanged method so I could set a max size for the customized trackball. Is there any way to solve this?

And FYI, the color of unselected legend without legendItemBuilder is not that dark in the same background.

Thanks for your time.

  _onActualRangeChanged(ActualRangeChangedArgs rangeChangedArgs) {
    if (_chartSeriesController != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (rangeChangedArgs.orientation == AxisOrientation.vertical) {
          if (rangeChangedArgs.axisName == 'primaryYAxis') {
            minInYAxis = rangeChangedArgs.visibleMin;
          }
        } else {
          CartesianChartPoint<DateTime> point = CartesianChartPoint(
              x: DateTime.fromMillisecondsSinceEpoch(
                  rangeChangedArgs.visibleMax.toInt()),
              y: minInYAxis);
          _bottomRight = _chartSeriesController!.pointToPixel(point);
        }
        SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
          count.value++;
        });
      });
    }
  }

@Hariram-SF4428
Copy link
Contributor

Hariram-SF4428 commented May 23, 2025

Hi @komhkomh,

Query 1: The color of unselected legend without legendItemBuilder is not that dark in the same background:

As mentioned in our previous update, we suspect that the toggled legend item’s color may be too close to the chart background when using legendItemBuilder, making it appear very dark when unselected. Without the legendItemBuilder, the default color is applied, which may explain the difference in appearance.

Since we do not know your exact application scenario, we are unable to proceed further on this. Therefore, we kindly request you to try replicating the reported issue in the test sample attached below and share the exact scenario to replicate the issue. This will help us assist you in a better way.

Image

Image

Query 2: I needed to calculate the size of plotarea in the onActualRangeChanged method so I could set a max size for the customized trackball:

We understand your requirement to access the plot area size for customizing the trackball. We already have a knowledge base article that demonstrates how to create a customized trackball. We have shared a knowledge base article link for your reference:

KB Link: How to customize the trackball in Flutter CartesianChart?

In this article, you’ll find an example that shows how to access the plot area size using the parentBox.paintBounds inside the custom TrackballBehavior class. This allows you to implement features such as setting a maximum size for the trackball tooltip or line, similar to what you're trying to achieve using chartSeriesController.

Here’s the relevant part from the sample:

final Rect plotAreaBounds = parentBox!.paintBounds;

This provides you the exact plot area boundaries without the need to rely on the chartSeriesController across all series.

Sample Link: flutter_cartesian_chart_customized_trackball/lib/main.dart at master · SyncfusionExamples/flutter_cartesian_chart_customized_trackball

Sample: gh_2355.zip

Please check and get back to us if you require further assistance.

Regards,
Hariram S

@LavanyaGowtham2021 LavanyaGowtham2021 added waiting for customer response Cannot make further progress until the customer responds. and removed open Open labels May 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
charts Charts component waiting for customer response Cannot make further progress until the customer responds.
Projects
None yet
Development

No branches or pull requests

4 participants