Reputation: 41
I am trying to display some data in a pie chart that is coming from an API but the problem is that how to apply the JSON data into a pie chart.
Upvotes: 0
Views: 4238
Reputation: 867
I've created a custom json for this.
Async function to get data from API
_getData() async{
final response = await http.get('https://api.myjson.com/bins/16e68w');
Map<String,dynamic> map = json.decode(response.body);
return map;
}
Returns json response as a Map<String, dynamic>
. I didn't parse json.
Scaffold(
body: FutureBuilder(
future: _getData(),
builder: (BuildContext context,AsyncSnapshot snapshot){
if(snapshot.connectionState == ConnectionState.done)
return new charts.PieChart(
dataList(snapshot.data),
defaultRenderer: new charts.ArcRendererConfig(
arcRendererDecorators: [new charts.ArcLabelDecorator()])
);
else
return Center(child: CircularProgressIndicator());
}
),
);
Format your data in charts.Series
list.
We'll generate a list of LinearSales object for data.
static List<charts.Series<LinearSales, int>> dataList(Map<String, dynamic> apiData) {
List<LinearSales> list = new List();
for(int i=0; i<apiData['data'].length; i++)
list.add(new LinearSales(i, apiData['data'][i]));
return [
new charts.Series<LinearSales, int>(
id: 'Sales',
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: list,
labelAccessorFn: (LinearSales row, _) => '${row.year}: ${row.sales}',
)
];
}
}
class LinearSales {
final int year;
final int sales;
LinearSales(this.year, this.sales);
}
Final Result
Upvotes: 4