I’m trying to plot the array received from an API into FlCharts but I’m not able to correctly iterate over the second level.
My array is as follows. I’m currently testing with static sample values which I’ll replace from actual response later. I have full control over the API that’s sending the values so please suggest if I should optimize the array structure.
var listData = [
{
'Product01': [12.0, 14.5, 15.6, 12.1, 15.2, 17.6, 12.8, 24.0, 35.4, 12.9]
},
{
'Product02': [9.0, 12.5, 11.6, 7.1, 10.2, 14.6, 8.8, 18.0, 31.4, 10.9]
},
];
The code I’m trying is as below:
var sections = listData.asMap().entries.map((data) {
final idx = data.key;
final listval = data.value;
return LineChartBarData(
spots: listval.asMap().entries.map((item) {
FlSpot(item.key, item.val);
}).toList(),
color: chartColors[idx],
barWidth: 5,
isCurved: true,
dotData: FlDotData(show: true),
);
}).toList();
and in the chart view
AspectRatio(
aspectRatio: 1.30,
child: LineChart(
LineChartData(
lineBarsData: sections,
),
The error I get is
lib/modules/home/widgets/yearly_expenses.dart:106:24: Error: The method 'asMap' isn't defined for the class 'Map<String, List<double>>'.
- 'Map' is from 'dart:core'.
- 'List' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named 'asMap'.
spots: listval.asMap().entries.map((item) {
^^^^^
I tried several variations (map, forEach) but none seems to work. I’m totally new to Dart coming from PHP. Any help is appreciated. Thanks in advance.
Edit: I updated my code as below, still get errors.
List sections = listData.asMap().entries.map((data) {
final idx = data.key;
final listval = data.value;
listval.entries.map((entry) {
final k = entry.key;
final v = entry.value;
return LineChartBarData(
spots: v.asMap().entries.map((data) {
return FlSpot(data.key, data.value);
}).toList(),
color: chartColors[idx],
barWidth: 5,
isCurved: true,
dotData: FlDotData(show: true),
);
}).toList();
}).toList();
This time the error is
Error: The argument type 'List<dynamic>' can't be assigned to the parameter type 'List<LineChartBarData>'.
- 'List' is from 'dart:core'.
- 'LineChartBarData' is from 'package:fl_chart/src/chart/line_chart/line_chart_data.dart' ('.pub-cache/hosted/pub.dev/fl_chart-0.69.0/lib/src/chart/line_chart/line_chart_data.dart').
lineBarsData: sections,
^
You have missed some important thing, when converting an existing List
to Map
, each item is associated to auto-incremented integer key
so that your list will become like the following:
{
1 :{
'Sales': [12.0, 14.5, 15.6, 12.1, 15.2, 17.6, 12.8, 24.0, 35.4, 12.9]
},
2 :{
'Cost': [9.0, 12.5, 11.6, 7.1, 10.2, 14.6, 8.8, 18.0, 31.4, 10.9]
},
}
You have treated the key correctly, but you forgot that the data associated with the key is itself an encapsulated Map
(Nested Map), so, it has its own key and value.
so to access that list :
listval = data.value['Sales'];
listval = data.value['Cost'];
3