Hello,
Is there a way to prevent exception when chart data is null or empty?
My flutter chart break when the data is empty
series: <LineSeries<MyChartData, String>>[
...chartData
.map((dt) => dt.country)
.toSet()
.map(
(country) =>
LineSeries<MyChartData, String>(
dataSource: chartData
.where((data) => data.country == country)
.toList(),
xValueMapper: (MyChartData data, _) =>
data.period,
yValueMapper: (MyChartData data, _) =>
data.value,
animationDuration: 700,
markerSettings: const MarkerSettings(
isVisible: true, height: 8, width: 8),
name: country,
dataLabelSettings: const DataLabelSettings(
// color: Colors.greenAccent,
labelAlignment: ChartDataLabelAlignment.top,
isVisible: true),
),
),
],
Regards
Sao
Hi Sao,
We have prepared a sample based on the provided code snippet and we were unable to replicate the mentioned exception when the data list is empty or when the data points are null or empty. However, if we specifically provide the data list as null, we can prevent the null exception by using the condition shown in the code snippet below:
class _MyAppState extends State<MyApp> { List<MyChartData> chartData = [];
@override void initState() { chartData = <MyChartData>[ MyChartData('0', 42, 'India'), MyChartData('1', 47, 'Russia'), MyChartData('2', 43, 'China'), MyChartData('3', 49, 'Korea'), MyChartData('4', 54, 'Africa'), MyChartData('5', 41, 'Australia'), ]; super.initState(); }
@override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: Center( child: SfCartesianChart( primaryXAxis: CategoryAxis(), primaryYAxis: NumericAxis(), series: <LineSeries<MyChartData, String>>[ if (chartData != null) ...chartData.map((dt) => dt.country).toSet().map( (country) => LineSeries<MyChartData, String>( dataSource: chartData .where((data) => data.country == country) .toList(), xValueMapper: (MyChartData data, _) => data.period, yValueMapper: (MyChartData data, _) => data.value, animationDuration: 700, markerSettings: const MarkerSettings( isVisible: true, height: 8, width: 8, ), name: country, dataLabelSettings: const DataLabelSettings( labelAlignment: ChartDataLabelAlignment.top, isVisible: true, ), ), ), ], ), ), ), ); } }
class MyChartData { MyChartData(this.period, this.value, this.country); final String? period; final num? value; final String? country; }
|
If you still encounter the exception when providing the data list as null or empty, we recommend that you modify the attached sample below to reproduce the mentioned exception. This will be very useful for us to provide the best possible solution from our end.
Regards,
Hari Hara Sudhan. K.