How to add a legend on pie chart from flutter (charts_flutter)?
Solution 1:
I implement a dirty solution. By adding new widget near pie chart as a legend.
Widget pieChart3()=>new Container(
color:Colors.white,
height: 220.0,
width: 220.0,
child:Stack(
children: <Widget>[
Positioned(
top: 50.0,
right: 10.0,
child: new Container(
height: 180,
width: 280,
color:Colors.white,
child:new charts.PieChart(seriesList,
animate: animate,
defaultRenderer: new charts.ArcRendererConfig(
arcRendererDecorators: [
new charts.ArcLabelDecorator(
//labelPadding:-25,
labelPosition: charts.ArcLabelPosition.outside),
],
arcWidth: 30,
)
)
)
),
Positioned(
bottom: 20.0,
left: 10.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children:listWidgets(slices)
),
),
]
)
);
and this lists legend items.
List<Widget> listWidgets(List<Slice> sliceList) {
List<Widget> list = sliceList == null ? new List() : sliceList.map((value) {
return new Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(width: 10.0),
Container(
color: Color.fromARGB(value.color.a, value.color.r, value.color.g,value.color.b),
width: 10.0,
height: 15.0,
),
Container(width: 5.0),
new Text(value.name),
]
);
}).toList();
return list;
}
and Slice class
class Slice {
final String name;
final int percent;
final Color color;
Slice(this.color,this.name, this.percent);
}
Defining slices
HashMap<int,int> sliceValues= new HashMap();
slices=new List();
sliceValues[1]=0;
sliceValues[2]=0;
sliceValues[3]=0;
sliceValues[4]=0;
sliceValues[5]=0;
for(Result r in items)
if(r.point<45)
if(sliceValues[1]==null)sliceValues[1]=1;
else sliceValues[1]=sliceValues[1]+1;
else if(r.point<55)
if(sliceValues[2]==null)sliceValues[2]=1;
else sliceValues[2]=sliceValues[2]+1;
else if(r.point<70)
if(sliceValues[3]==null)sliceValues[3]=1;
else sliceValues[3]=sliceValues[3]+1;
else if(r.point<85)
if(sliceValues[4]==null)sliceValues[4]=1;
else sliceValues[4]=sliceValues[4]+1;
else
if(sliceValues[5]==null)sliceValues[5]=1;
else sliceValues[5]=sliceValues[5]+1;
for(int key in sliceValues.keys)
slices.add(new Slice(
key==1?charts.MaterialPalette.red.shadeDefault.darker:
key==2?charts.MaterialPalette.deepOrange.shadeDefault.darker:
key==3?charts.MaterialPalette.yellow.shadeDefault.darker:
key==4?charts.MaterialPalette.blue.shadeDefault.darker:
key==5?charts.MaterialPalette.green.shadeDefault.darker:
charts.MaterialPalette.black,
key==1?"0-44":
key==2?"45-54":
key==3?"55-69":
key==4?"70-84":
key==5?"85+":
"",
items.length>0?100*sliceValues[key]~/items.length:0));