How to clear chart_bar selectedDatum in Flutter - flutter

I have a barchart ,when I click line it will navigate to new page.
I use model.selectedDatum.clear();
but when back to chart page , it is still select,it not working.
How can I set it unselect , when I back to chart page, thank you.
Widget build(BuildContext context) {
return SizedBox(
height: 400,
child: charts.BarChart(
_createSampleData(),
animate: true,
vertical: false,
selectionModels: [
charts.SelectionModelConfig(
type: charts.SelectionModelType.info,
changedListener: (charts.SelectionModel model) {
if (model.hasDatumSelection) {
int month = model.selectedDatum[0].index! + 1;
Get.toNamed(RouteTable.expenseDetailList,
arguments: [_.currentYear, month, _.barSegmentIndex])?.then((value)=>
model.selectedDatum.clear());
}
},)
],
barRendererDecorator: charts.BarLabelDecorator<String>(
labelAnchor: charts.BarLabelAnchor.end),
));
}
List<charts.Series<double, String>> _createSampleData() {
return [
charts.Series<double, String>(
id: 'Month',
domainFn: (value, ix) => months[ix ?? 0],
measureFn: (value, ix) => value,
colorFn: ((value, ix) => charts.Color.fromHex(code: colors[index])),
data: data,
labelAccessorFn: (value, _) => nf.format(value))
];
}

Override userManagedState to handle selectionModels
final _myState = charts.UserManagedState<String>();
#override
Widget build(BuildContext context) {
final chart = charts.BarChart(
// ...
// 1. override userManagedState
userManagedState: _myState,
selectionModels: [
charts.SelectionModelConfig(
changedListener: (model) {
// 2. clear selectionModels
setState(() {
_myState.selectionModels[charts.SelectionModelType.info] = charts.UserManagedSelectionModel();
});
},
],
);
// ...
}

Related

how to display graph in flutter

Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
// Enables the legend
legend: Legend(isVisible: true),
// Initialize category axis
primaryXAxis: CategoryAxis(),
series: <ChartSeries>[
// Initialize line series
LineSeries<GraphModel, String>(
dataSource: [
// Bind data source
// retrieve data from database
GraphModel(
productName: ['prodName'], count: 'count'.length
),
],
xValueMapper: (GraphModel data, _) => data.productName,
yValueMapper: (GraphModel data, _) => data.count,
)
]
)
)
)
);
}
}
I want to retrieve data from firestore where I create GraphModel but i dont know to declare from firebase to input in the graph. Please help me how to declare this graph
need to import the cloud_firestore package to your pubspec.yaml file
Heres the full code to retrieve data from firestore:
import 'package:cloud_firestore/cloud_firestore.dart';
class GraphModel {
String productName;
int count;
GraphModel({this.productName, this.count});
}
class YourWidget extends StatefulWidget {
#override
_YourWidgetState createState() => _YourWidgetState();
}
class _YourWidgetState extends State<YourWidget> {
List<GraphModel> _graphData = [];
#override
void initState() {
super.initState();
_retrieveDataFromFirestore();
}
void _retrieveDataFromFirestore() async {
final firestore = FirebaseFirestore.instance;
final graphData = await firestore.collection('your_collection').get();
setState(() {
_graphData = graphData.docs.map((doc) => GraphModel(
productName: doc.data()['product_name'],
count: doc.data()['count'],
)).toList();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
legend: Legend(isVisible: true),
primaryXAxis: CategoryAxis(),
series: <ChartSeries>[
LineSeries<GraphModel, String>(
dataSource: _graphData,
xValueMapper: (GraphModel data, _) => data.productName,
yValueMapper: (GraphModel data, _) => data.count,
),
],
),
),
),
);
}
}

How to fix Lateinitializationerror in flutter [duplicate]

This question already has answers here:
LateError (LateInitializationError: Field 'latitude' has not been initialized.)
(4 answers)
Closed 4 months ago.
I have a minor bug in my flutter app, it is trying to display a chart of users but before it does it will first display Lateinitializationerror. But then after a few seconds it runs the way I want it to be. How can I fix that bug? Here is my code.
class _AdminDashboardState extends State<AdminDashboard> {
late List<USERdata>? _chartData;
late TooltipBehavior _tooltipbehaviorpie;
#override
void initState() {
getDataFromDatabase().then((value) {
_chartData = getChartData();
_tooltipbehaviorpie = TooltipBehavior(enable: true);
}).whenComplete(() => setState(
() {},
));
super.initState();
}
var mentor_count;
var incubate_count;
Future getDataFromDatabase() async {
final CollectionReference collectionRefIncubate =
FirebaseFirestore.instance.collection('incubatees');
QuerySnapshot querySnapshotIncubate = await collectionRefIncubate.get();
final length1 = querySnapshotIncubate.docs.length;
incubate_count = length1;
final CollectionReference collectionRefMentor =
FirebaseFirestore.instance.collection('mentors');
QuerySnapshot querySnapshotMentor = await collectionRefMentor.get();
final length2 = querySnapshotMentor.docs.length;
mentor_count = length2;
}
#override
Widget build(BuildContext context) {
//users chart
final userData = Container(
decoration: BoxDecoration(border: Border.all(color: Colors.black)),
margin: const EdgeInsets.symmetric(horizontal: 20),
height: MediaQuery.of(context).size.height * 0.30,
child: SfCircularChart(
title: ChartTitle(text: 'Users\n(Mentors & Incubates)'),
legend: Legend(
isVisible: true,
overflowMode: LegendItemOverflowMode.wrap,
),
tooltipBehavior: _tooltipbehaviorpie,
series: <CircularSeries>[
PieSeries<USERdata, String>(
dataSource: _chartData,
xValueMapper: (USERdata data, _) => data.user,
yValueMapper: (USERdata data, _) => data.count,
dataLabelSettings: const DataLabelSettings(
isVisible: true,
labelAlignment: ChartDataLabelAlignment.top,
),
enableTooltip: true,
// maximumValue: 40000,
)
],
),
);
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: const Text("Dashboard"),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
userData,
],
),
)));
}
List<USERdata> getChartData() {
final List<USERdata> chartData = [
USERdata('Mentors', mentor_count),
USERdata('Incubatees', incubate_count),
];
return chartData;
}
}
I created late initializations first that will be used for my pie chart, and called the initstate to put them values. The error occurs after I hot restart, but a few seconds after that, it runs the way I want them to be. Is there a way on how to fix this bug?
In this case you should change your late variable to nullable variable:
List<USERdata>? _chartData;
TooltipBehavior? _tooltipbehaviorpie;
and in your build method, check:
#override
Widget build(BuildContext context) {
if (_chartData == null || _tooltipbehaviorpie == null) {
return const SizedBox(); //may be change your loading widget here
}
// from here you can use _chartData! and tooltipbehaviorpie!
return yourWidget();
}

Flutter - Using API for charts with model

i've got stuck at this problem for nearly 3 days. Already post it in another questions but, got minus instead an answer.
Let me make it clear the questions.
I would like to put my api data using models into chart flutter, here is my code
First is my model here is my age model
ages.dart
Ages agesFromJson(String str) => Ages.fromJson(json.decode(str));
String agesToJson(Ages data) => json.encode(data.toJson());
class Ages {
Ages({
this.entity,
this.code,
this.year,
this.underAge15,
this.age1564,
this.age65Over,
});
String entity;
String code;
int year;
String underAge15;
String age1564;
String age65Over;
factory Ages.fromJson(Map<String, dynamic> json) => Ages(
entity: json["entity"],
code: json["code"],
year: json["year"],
underAge15: json["under_age_15"],
age1564: json["age_15_64"],
age65Over: json["age_65_over"],
);
Map<String, dynamic> toJson() => {
"entity": entity,
"code": code,
"year": year,
"under_age_15": underAge15,
"age_15_64": age1564,
"age_65_over": age65Over,
};
}
and here i make the ages chart that given me the url from api and put into future builder
ages_chart.dart
class AgeCharts extends StatefulWidget {
final String url;
const AgeCharts({this.url});
#override
_AgeChartsState createState() => _AgeChartsState();
}
class _AgeChartsState extends State<AgeCharts> {
var chart;
#override
void initState() {
// TODO: implement initState
super.initState();
}
#override
Widget build(BuildContext context) {
print(widget.url);
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Japanese Age Working Populations'),
),
body: Container(
height: 400,
child: FutureBuilder<List>(
future: getChartData(widget),
builder: (context, dataapi) {
if (dataapi.hasError) print(dataapi.error);
print(dataapi);
return dataapi.hasData
? ShowChart(
data: dataapi.data,
)
: Center(
child: CircularProgressIndicator(),
);
},
),
),
),
);
}
}
after ages dart, i make a function to get an api.
Future<List> getChartData(widget) async {
final response = await http.get(widget.url);
return json.decode(response.body)['data'];
}
and here is my show chart when i already get an url
class ShowChart extends StatelessWidget {
final List data;
ShowChart({this.data});
static List<charts.Series<Ages, dynamic>> _createSampleData(dataAPI) {
return [
new charts.Series<Ages, dynamic>(
id: 'Desktop',
// colorFn specifies that the line will be blue.
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
// areaColorFn specifies that the area skirt will be light blue.
areaColorFn: (_, __) =>
charts.MaterialPalette.blue.shadeDefault.lighter,
domainFn: (Ages ages, _) => ages.year,
measureFn: (Ages ages, _) => int.parse(ages.underAge15),
data: dataAPI,
),
new charts.Series<Ages, dynamic>(
id: 'Tablet',
// colorFn specifies that the line will be red.
colorFn: (_, __) => charts.MaterialPalette.red.shadeDefault,
// areaColorFn specifies that the area skirt will be light red.
areaColorFn: (_, __) => charts.MaterialPalette.red.shadeDefault.lighter,
domainFn: (Ages ages, _) => ages.year,
measureFn: (Ages ages, _) => int.parse(ages.age1564),
data: dataAPI,
),
new charts.Series<Ages, dynamic>(
id: 'Mobile',
// colorFn specifies that the line will be green.
colorFn: (_, __) => charts.MaterialPalette.green.shadeDefault,
// areaColorFn specifies that the area skirt will be light green.
areaColorFn: (_, __) =>
charts.MaterialPalette.green.shadeDefault.lighter,
domainFn: (Ages ages, _) => ages.year,
measureFn: (Ages ages, _) => int.parse(ages.age65Over),
data: dataAPI,
),
];
}
#override
Widget build(BuildContext context) {
print('showchart');
print(data);
return Container(
child: charts.LineChart(
_createSampleData(data),
defaultRenderer:
new charts.LineRendererConfig(includeArea: true, stacked: true),
animate: true,
),
);
}
}
this is my JSON Structure. but i get the data when using json.decode(response.body)
{
"status": true,
"message": "Chart found",
"data": [
{
"entity": "Japan",
"code": "JPN",
"year": 1950,
"under_age_15": "29288.106",
"age_15_64": "49447.555",
"age_65_over": "4066.423"
},
{
"entity": "Japan",
"code": "JPN",
"year": 1951,
"under_age_15": "29652.515",
"age_15_64": "50461.828",
"age_65_over": "4201.922"
},
]
}
and the i got an error like this
type 'List<dynamic>' is not a subtype of type 'List<Ages>'
help me solve the problem, please
Problems within your code:
You are explicitly casting your series data as charts.Series<Ages, dynamic> while it should be charts.Series<Ages, num>
You are trying to parse double as int. If you want doubles, use double.parse(x) otherwise, double.parse(x).round() will give you a int. (or .floor() or .ceil())
You should probably also specify your domain axis as not being zeroBound:
charts.LineChart(
_createSampleData(data),
defaultRenderer: charts.LineRendererConfig(includeArea: true, stacked: true),
animate: true,
domainAxis: charts.NumericAxisSpec(
tickProviderSpec: charts.BasicNumericTickProviderSpec(zeroBound: false),
),
),
Working Solution
Full source code for easy copy-paste
import 'dart:math' as math;
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Charts Demo',
home:
AgeCharts(url: 'http://udacoding-task-api.herokuapp.com/api/charts'),
),
);
}
// MAIN WIDGET
class AgeCharts extends StatefulWidget {
final String url;
const AgeCharts({this.url});
#override
_AgeChartsState createState() => _AgeChartsState();
}
class _AgeChartsState extends State<AgeCharts> {
var chart;
Future<List<Ages>> getChartData(widget) async {
final response = await http.get(widget.url);
final List<dynamic> jsonData = jsonDecode(response.body)['data'];
return jsonData.map((data) => Ages.fromJson(data)).toList();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Japanese Age Working Populations'),
),
body: Padding(
padding: EdgeInsets.all(8.0),
child: FutureBuilder<List>(
future: getChartData(widget),
builder: (context, dataapi) {
if (dataapi.hasError) print(dataapi.error);
return dataapi.hasData
? ShowChart(data: dataapi.data)
: Center(child: CircularProgressIndicator());
},
),
),
),
);
}
}
// CHART
class ShowChart extends StatelessWidget {
final List<Ages> data;
ShowChart({this.data});
static List<charts.Series<Ages, num>> _createSampleData(dataAPI) {
return [
new charts.Series<Ages, num>(
id: 'underAge15',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
areaColorFn: (_, __) =>
charts.MaterialPalette.blue.shadeDefault.lighter,
domainFn: (Ages ages, _) => ages.year,
measureFn: (Ages ages, _) => double.parse(ages.underAge15).round(),
data: dataAPI,
),
new charts.Series<Ages, num>(
id: 'age1564',
colorFn: (_, __) => charts.MaterialPalette.red.shadeDefault,
areaColorFn: (_, __) => charts.MaterialPalette.red.shadeDefault.lighter,
domainFn: (Ages ages, _) => ages.year,
measureFn: (Ages ages, _) => double.parse(ages.age1564).round(),
data: dataAPI,
),
new charts.Series<Ages, num>(
id: 'age65Over',
colorFn: (_, __) => charts.MaterialPalette.green.shadeDefault,
areaColorFn: (_, __) =>
charts.MaterialPalette.green.shadeDefault.lighter,
domainFn: (Ages ages, _) => ages.year,
measureFn: (Ages ages, _) => double.parse(ages.age65Over).round(),
data: dataAPI,
),
];
}
#override
Widget build(BuildContext context) {
return Container(
child: charts.LineChart(
_createSampleData(data),
defaultRenderer:
new charts.LineRendererConfig(includeArea: true, stacked: true),
animate: true,
domainAxis: charts.NumericAxisSpec(
tickProviderSpec:
charts.BasicNumericTickProviderSpec(zeroBound: false),
),
),
);
}
}
// DOMAIN
class Ages {
Ages({
this.entity,
this.code,
this.year,
this.underAge15,
this.age1564,
this.age65Over,
});
String entity;
String code;
int year;
String underAge15;
String age1564;
String age65Over;
factory Ages.fromJson(Map<String, dynamic> json) => Ages(
entity: json["entity"],
code: json["code"],
year: json["year"],
underAge15: json["under_age_15"],
age1564: json["age_15_64"],
age65Over: json["age_65_over"],
);
Map<String, dynamic> toJson() => {
"entity": entity,
"code": code,
"year": year,
"under_age_15": underAge15,
"age_15_64": age1564,
"age_65_over": age65Over,
};
}
// DATA
math.Random random = math.Random();
final Map<String, dynamic> data = {
"status": true,
"message": "Chart found",
"data": List.generate(
20,
(index) => {
"entity": "Japan",
"code": "JPN",
"year": 1950 + index,
"under_age_15": (25000 + random.nextInt(5000)).toString(),
"age_15_64": (40000 + random.nextInt(5000)).toString(),
"age_65_over": (3000 + random.nextInt(2000)).toString(),
}).toList(),
};
BEFORE ANSWER UPDATE:
Try this:
Future<List<Ages>> getChartData(widget) async {
final response = await http.get(widget.url);
return json.decode(response.body)['data'].map((jsonData) => Ages.fromJson(jsonData)).toList();
}
I'm not 100% sure, since I don't know the structure of your JSON Data.

How to show line chart from data json using flutter

i will display linechart from the database using datajson with flutter. but the reference that I can use is hardcode data. Please help
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:charts_flutter/flutter.dart' as charts;
int dataTotal = 0;
class GrafikSpbj extends StatefulWidget {
final List<charts.Series> seriesList;
final bool animate;
GrafikSpbj(this.seriesList, {this.animate});
/// Creates a [LineChart] with sample data and no transition.
factory GrafikSpbj.withSampleData() {
return new GrafikSpbj(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
_GrafikSpbjState createState() => _GrafikSpbjState();
/// Create one series with sample hard coded data.
static List<charts.Series<LinearSales, int>> _createSampleData() {
print(dataTotal);
final desktopSalesData = [
new LinearSales(0, 10),
new LinearSales(1, 50),
new LinearSales(2, 70),
new LinearSales(3, 100),
];
final tableSalesData = [
new LinearSales(0, 20),
new LinearSales(1, 40),
new LinearSales(2, 80),
new LinearSales(3, 100),
];
return [
new charts.Series<LinearSales, int>(
id: 'Desktop',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: desktopSalesData,
),
new charts.Series<LinearSales, int>(
id: 'Tablet',
colorFn: (_, __) => charts.MaterialPalette.red.shadeDefault,
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: tableSalesData,
),
];
}
}
class _GrafikSpbjState extends State<GrafikSpbj> {
List data;
Timer timer;
int jumlahData = 0;
Future<List> _getData() async {
final response = await http.get("xxxxxxxxxxxxx");
setState(() {
data = json.decode(response.body);
jumlahData =data.length;
print(data[0]['id_spbj']);
print(data[0]['minggu_ke']);
print(data[0]['hasil']);
print(data[0]['target_grafik']);
});
return json.decode(response.body);
}
// makeRequest() async {
// var response = await http.get(
// 'xxxxxxxxxxxxxxxxxxxxxxx',
// headers: {'Accept': 'application/json'},
// );
// setState(() {
// data = json.decode(response.body);
// jumlahData =data.length;
// });
// }
#override
void initState() {
_getData();
dataTotal = jumlahData;
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Text("Input Pelanggan hal 2"),
),
body: Column(
children: <Widget>[
SizedBox(
width: 600.0,
height: 250.0,
child: new charts.NumericComboChart(widget.seriesList,
animate: widget.animate,
defaultRenderer: new charts.LineRendererConfig(),
customSeriesRenderers: [
new charts.PointRendererConfig(customRendererId: 'customPoint')
]),
),
new Text("data"),
new Text("data"),
new Text("data")
],
),
);
}
}
/// Sample linear data type.
class LinearSales {
final int year;
final int sales;
LinearSales(this.year, this.sales);
}
values
[{"id_spbj":"1","minggu_ke":"1","hasil":"13.4353337","target_grafik":"25.00"},{"id_spbj":"1","minggu_ke":"2","hasil":"28.2629147","target_grafik":"25.00"},{"id_spbj":"1","minggu_ke":"3","hasil":"85.3285762","target_grafik":"25.00"},{"id_spbj":"2","minggu_ke":"1","hasil":"32.0184122","target_grafik":"25.00"},{"id_spbj":"2","minggu_ke":"2","hasil":"53.5296934","target_grafik":"25.00"}]
You can use FL_chart plugin library in flutter, where you draw all types of charts.
please find guideline to use FL_Chart

Why I cant make a class string as domainFn for pie chart in charts_flutter

Hi there I am trying to make Piechart base on its example
But I change Just one thing, I changed
final int year
to
final String year
but for domainFn Im getting this error:
{
"resource": "/home/saeb/AndroidStudioProjects/charts/lib/main.dart",
"owner": "dart",
"code": "return_of_invalid_type_from_closure",
"severity": 8,
"message": "The return type 'String' isn't a 'int', as defined by anonymous closure.",
"source": "dart",
"startLineNumber": 36,
"startColumn": 45,
"endLineNumber": 36,
"endColumn": 55,
"tags": []
}
my label should be string not int, how I can do that?
my code:
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
class PieOutsideLabelChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
PieOutsideLabelChart(this.seriesList, {this.animate});
factory PieOutsideLabelChart.withSampleData() {
return new PieOutsideLabelChart(
_createSampleData(),
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.PieChart(seriesList,
animate: animate,
defaultRenderer: new charts.ArcRendererConfig(arcRendererDecorators: [
new charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.outside)
]));
}
static List<charts.Series<LinearSales, int>> _createSampleData() {
final data = [
new LinearSales('a long text', 100),
new LinearSales('even longer text', 75),
new LinearSales('i am long text', 25),
new LinearSales('the longest text ever', 5),
];
return [
new charts.Series<LinearSales, int>(
id: 'Sales',
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: data,
labelAccessorFn: (LinearSales row, _) => '${row.year}: ${row.sales}',
)
];
}
}
class LinearSales {
final String year;
final int sales;
LinearSales(this.year, this.sales);
}
main(List<String> args) {
runApp(MaterialApp(
title: 'charts',
home: new Scaffold(
appBar: new AppBar(title: new Text("نمودار فلان"),),
body:new ListView(children: <Widget>[
new Card
(child: PieOutsideLabelChart(PieOutsideLabelChart._createSampleData()),)
// ]
// ),
]
)
)
)
);
}
It was syntax problem. my bad :D
I should change my charts.Series to charts.Series<LinearSales, **String**>> from charts.Series<LinearSales, **int**>>
this code works:
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
class PieOutsideLabelChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
PieOutsideLabelChart(this.seriesList, {this.animate});
factory PieOutsideLabelChart.withSampleData() {
return new PieOutsideLabelChart(
_createSampleData(),
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.PieChart(seriesList,
animate: animate,
defaultRenderer: new charts.ArcRendererConfig(arcRendererDecorators: [
new charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.outside)
]));
}
static List<charts.Series<LinearSales, String>> _createSampleData() {
final data = [
new LinearSales('a long text', 100),
new LinearSales('even longer text', 75),
new LinearSales('i am long text', 25),
new LinearSales('the longest text ever', 5),
];
return [
new charts.Series<LinearSales, String>(
id: 'Sales',
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: data,
labelAccessorFn: (LinearSales row, _) => '${row.year}',
)
];
}
}
class LinearSales {
final String year;
final int sales;
LinearSales(this.year, this.sales);
}
main(List<String> args) {
runApp(MaterialApp(
title: 'charts',
home: new Scaffold(
appBar: new AppBar(title: new Text("نمودار فلان"),),
body: PieOutsideLabelChart(PieOutsideLabelChart._createSampleData()),)
)
);
}
you can make a class string as domainFn for pie chart in charts_flutter.
it will take some adjustments
Step 1: Add this to your chart so it gonna show label on outside of pie chart
defaultRenderer: new charts.ArcRendererConfig(
arcWidth: 60,
arcRendererDecorators: [new charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.outside)]
),
Step 2 : Now for customization of those label with string there on property.
which is labelAccessorFn
String datas(int id,int value){
if(id==0){
return value.toString()+":RT";
}else if(id==1){
return value.toString()+":OT";
}
else if(id==2){
return value.toString()+":IT";
}
return [
new charts.Series<VfmProductivityPie, int>(
id: 'Sales',
domainFn: (VfmProductivityPie sales, _) => sales.id,
measureFn: (VfmProductivityPie sales, _) => sales.value,
data: data,
labelAccessorFn: (VfmProductivityPie row, _) =>
// print('object'),
//'${row.id}r: ${row.value}',
datas(row.id,row.value)
)
];
Note: write data function under _createSampleDataworking screenshot of piechart
Its very simple:
set year variable to int again:
final int year
and here use toString() method:
labelAccessorFn: (LinearSales row, _) => '${row.year.toString()}: ${row.sales}',